简单的Bash脚本:有什么问题?

时间:2015-05-04 18:26:45

标签: bash

我正在使用Ubuntu Server:

#uname -a
Linux grosella 3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

设置这样的数据文件(/tmp/data.txt):

1 AAAA
2 BBBB
3 CCCC
4 DDDD
5 EEEE
6 FFFF

运行以下Bash脚本:

typeset -i ACUM=0
typeset -a V=('')

cat /tmp/data.txt | \
while read LINEA ; do
  [ "x$LINEA" == "x" ] && break
  V=( $LINEA )
  VAL="${V[0]}"
  [ "x$VAL" == "x" ] && continue
  [[ $VAL =~ ^[0-9]+$ ]] || continue
  ((ACUM+=VAL))
  echo -e "VAL=$VAL\t\tACUM=$ACUM"
done

echo -e "\nFinal Result: $ACUM"

以下是打印输出:

VAL=1       ACUM=1
VAL=2       ACUM=3
VAL=3       ACUM=6
VAL=4       ACUM=10
VAL=5       ACUM=15
VAL=6       ACUM=21

Final Result: 0

而不是21,最终结果为0.出了什么问题?

2 个答案:

答案 0 :(得分:3)

将数据传输到while循环时,会创建while循环运行的子shell。子shell不能改变父级的环境变量,因此外部<!-- Facebook pixel --> <script>(function() { var _fbq = window._fbq || (window._fbq = []); if (!_fbq.loaded) { var fbds = document.createElement('script'); fbds.async = true; fbds.src = '//connect.facebook.net/en_US/fbds.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(fbds, s); _fbq.loaded = true; } _fbq.push(['addPixelId', 'thisismysecretid']); })(); window._fbq = window._fbq || []; window._fbq.push(['track', 'PixelInitialized', {}]); </script> <noscript><img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/tr?id=938407189542791&amp;ev=PixelInitialized" /></noscript> 不会改变。

答案 1 :(得分:2)

更改您的代码
cat /tmp/data.txt | \
while read LINEA ; do
  # ...
done

while read LINEA ; do
  # ...
done < /tmp/data.txt

避免两个具有自己环境的子壳。