在while循环内修改的变量不被记住 [英] A variable modified inside a while loop is not remembered
问题描述
在下面的程序中,如果我在第一个if
语句中将变量$foo
设置为值1,则它的工作方式是在if语句之后记住其值.但是,当我在while
语句内的if
中将相同的变量设置为值2时,在while
循环之后将其忘记.就像我在while
循环中使用某种类型的变量$foo
的副本一样,而我仅在修改该特定副本.这是完整的测试程序:
In the following program, if I set the variable $foo
to the value 1 inside the first if
statement, it works in the sense that its value is remembered after the if statement. However, when I set the same variable to the value 2 inside an if
which is inside a while
statement, it's forgotten after the while
loop. It's behaving like I'm using some sort of copy of the variable $foo
inside the while
loop and I am modifying only that particular copy. Here's a complete test program:
#!/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退出,您对变量所做的任何更改将不可用.
The while
loop is executed in a subshell. So any changes you do to the variable will not be available once the subshell exits.
相反,您可以使用 此处为字符串 重写在主shell进程中的while循环;只有echo -e $lines
会在子Shell中运行:
Instead you can use a here string to re-write the while loop to be in the main shell process; only echo -e $lines
will run in a subshell:
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")"
您可以通过在分配lines
时立即展开反斜杠序列来摆脱上面的此处字符串中难看的echo
.可以在其中使用$'...'
报价形式:
You can get rid of the rather ugly echo
in the here-string above by expanding the backslash sequences immediately when assigning lines
. The $'...'
form of quoting can be used there:
lines=$'first line\nsecond line\nthird line'
while read line; do
...
done <<< "$lines"
这篇关于在while循环内修改的变量不被记住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!