在下面的程序中,如果我$foo在第一个if语句中将变量设置为值1 ,那么它的作用就是在if语句之后记住它的值.但是,当我将同一个变量设置if为while语句内部的值2时,它在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 …Run Code Online (Sandbox Code Playgroud)