内循环的同时不记得修改变量 [英] Modifying variable inside while loop is not remembered
问题描述
在下面的程序,如果我设置变量 $ foo的
来的第一个如果
语句中值1 ,它工作在这个意义上,它的价值是if语句后,记住了。然而,当我同一个变量的值设置为2内的如果
这是一个,而
语句中,它被遗忘在,而
循环。它的行为就像我使用某种变量的副本 $ foo的
的,而
循环中,我修改只有特定的副本。下面是一个完整的测试程序:
#!/斌/庆典设置-e
设置-u富= 0
酒吧=你好如果[$栏==你好]
然后
富= 1
回声设置\\ $ foo的1:$富
科幻
回声变量\\ $ foo的if语句后:$富行=第一行\\ n第二行\\ nthird线回声-e $线|而读线
做
如果[$线==二线]
然后
富= 2
回声变\\ $ foo的更新为foo $如果里面,而里面的循环
科幻
回声\\ $ foo的价值在while循环体:$富
DONE回声变量\\ $ foo的后while循环:$富#输出:
#$ ./testbash.sh
#设置$ foo的1:1
if语句后#变量$ foo的:1
在while循环体的$ foo的#值:1
#变量$ foo的更新,以2内,如果内部while循环
在while循环体的$ foo的#值:2
在while循环体的$ foo的#值:2
#while循环之后变量$ foo的:1#庆典--version
#GNU的bash,版本4.1.10(4) - 释放(i686的-PC-cygwin的)
感谢您的阅读,并在此先感谢您的帮助!
回声-e $线|而读线
...
DONE
在子shell执行的,而
是循环。所以,你的变量做任何修改将无法使用,一旦子shell退出。
相反,你可以重新编写while循环是在一个主shell进程;仅回声-e $行
将在子shell中运行:
而读线
做
如果[$线==二线]
然后
富= 2
回声变\\ $ foo的更新为foo $如果里面,而里面的循环
科幻
回声\\ $ foo的价值在while循环体:$富
完成<<< $(回声-e$行)
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)
Thanks for reading and thanks in advance for any help!
echo -e $lines | while read line
...
done
The while
is loop executed in a subshell. So any changes you do for the variable will not be available once the subshell exits.
Instead you can re-write the while loop to be in a 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")"
这篇关于内循环的同时不记得修改变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!