在下面的程序中,如果我在第一个 if
语句中将变量 $foo
设置为值 1,那么它的工作原理是在之后记住它的值if 语句。但是,当我在 while
语句内的 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 中执行。因此,一旦子 shell 退出,您对变量所做的任何更改都将不可用。
您可以使用 here string重写 while 循环以使其位于主 shell 进程中;只有 echo -e $lines
会在子 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")"
您可以通过在分配行
时立即展开反斜杠序列来消除上面字符串中相当难看的echo
。可以在此处使用 $'...'
形式的引用:
lines=$'first line\nsecond line\nthird line'
while read line; do
...
done <<< "$lines"
关于bash - 在 while 循环内修改的变量不会被记住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37273933/