【发布时间】:2013-05-27 02:20:36
【问题描述】:
在下面的程序中,如果我在第一个 if 语句中将变量 $foo 设置为值 1,它的工作原理是在 if 语句之后记住它的值。但是,当我在 if(位于 while 语句中)内将相同的变量设置为值 2 时,在 while 循环之后会忘记它。这就像我在while 循环中使用变量$foo 的某种副本,我只修改那个特定的副本。这是一个完整的测试程序:
#!/bin/bash
set -e
set -u
foo=0
bar="hello"
if [[ "$bar" == "hello" ]]
then
foo=1
echo "Setting \$foo to 1: $foo"
fi
echo "Variable \$foo after if statement: $foo"
lines="first line\nsecond line\nthird line"
echo -e $lines | while read line
do
if [[ "$line" == "second line" ]]
then
foo=2
echo "Variable \$foo updated to $foo inside if inside while loop"
fi
echo "Value of \$foo in while loop body: $foo"
done
echo "Variable \$foo after while loop: $foo"
# Output:
# $ ./testbash.sh
# Setting $foo to 1: 1
# Variable $foo after if statement: 1
# Value of $foo in while loop body: 1
# Variable $foo updated to 2 inside if inside while loop
# Value of $foo in while loop body: 2
# Value of $foo in while loop body: 2
# Variable $foo after while loop: 1
# bash --version
# GNU bash, version 4.1.10(4)-release (i686-pc-cygwin)
【问题讨论】:
-
shellcheck 实用程序捕获了这个(参见github.com/koalaman/shellcheck/wiki/SC2030);将上述代码剪切并粘贴到shellcheck.net 中会针对第 19 行发出此反馈:
SC2030: Modification of foo is local (to subshell caused by pipeline).
标签: bash while-loop scope sh