星期四, 五月 17, 2007

bash while read line and variable scope?

比较下面两个 bash 脚本:
script (1)
echo -e "aaa\nbbb\nccc\nddd" >tmpfile
value=0
while read line; do
value=`expr $value + 1`
echo $value;
done "<"tmpfile
echo "at last: $value"

result:
1
2
3
4
at last: 4

script (2):
value=0
echo -e "aaa\nbbb\nccc\nddd" | while read line; do
value=`expr $value + 1`
echo $value
done
echo "at last: $value"

result:
1
2
3
4
at last: 0
在第二个脚本中,全局变量的变更没有起作用。这是因为 bash 中管道是在子 shell 中执行的。所以这里只能使用重定向。

参考:comp.unix.shell FAQ
This is because in the Bourne shell redirected control structures
run in a subshell
In shells other than ksh (not pdksh) and
zsh elements of a pipeline are run in subshells.


可以用如下的脚本验证
#!/bin/sh

echo -e "aaa" >tmpfile
while read line; do
ps aux | grep "$0" | grep -v grep
done "<"tmpfile
rm -f tmpfile

echo "---"
echo -e "aaa" | while read line; do
ps aux | grep "$0" | grep -v grep
done

没有评论: