在下面的程序中,如果我将变量$ foo设置为第一个if语句中的值1,它的意思是它的值在if语句之后被记住。但是,当我将一个相同的变量设置为一个if语句中的if里面的值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)
感谢您的阅读和提前感谢任何帮助!
echo -e $lines | while read line ... done
while是在子shell中循环执行的。因此,对子变量退出后,对变量所做的任何更改都不可用。
相反,你可以使用here string重写while循环在主shell进程中;只有echo -e $行将在子shell中运行:
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 -e "$lines")"