在下面的程序中,如果我$foo在第一个语句中将变量设置为值 1 if,则它的工作原理是在 if 语句之后记住它的值。if但是,当我在语句中的 an 中将相同的变量设置为值 2 时,它在循环while后被遗忘了。它的行为就像我在循环内while使用某种变量的副本,我只修改那个特定的副本。这是一个完整的测试程序:$foo``while
$foo
if
while
$foo``while
#!/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 中执行。因此,一旦子shell 退出,您对变量所做的任何更改都将不可用。
相反,您可以使用 here 字符串 将 while 循环重新编写到主 shell 进程中;只会echo -e $lines在子shell中运行:
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 -e "$lines")"
您可以echo通过在分配lines. 引用的$'...'形式可以在那里使用:
echo
lines
$'...'
lines=$'first line\nsecond line\nthird line' while read line; do ... done <<< "$lines"