In BASH, a variable is changed in a loop, but is kept untouched when quit loop; i.e, the new value set in loop is lost.
function showme
{
echo -n "Loop=$linecount"
sh -c 'echo " PID=$PPID"'
}
echo "========1======="
linecount=0
showme
echo "111 222 333" | tr ' ' '\n' | while read LINE
do
(( linecount = linecount + 1 ))
showme
done
showme
echo "========2======="
linecount=0
showme
while read LINE
do
(( linecount = linecount + 1 ))
showme
done <<-EOF
$(echo "111 222 333" | tr ' ' '\n')
EOF
showme
The execute output:
$ bash t.sh
========1=======
Loop=0 PID=2620
Loop=1 PID=2647
Loop=2 PID=2647
Loop=3 PID=2647
Loop=0 PID=2620
========2=======
Loop=0 PID=2620
Loop=1 PID=2620
Loop=2 PID=2620
Loop=3 PID=2620
Loop=3 PID=2620
the same script when execute using ksh, the output is different:
$ ksh t.sh
========1=======
Loop=0 PID=12090
Loop=1 PID=12090
Loop=2 PID=12090
Loop=3 PID=12090
Loop=3 PID=12090
========2=======
Loop=0 PID=12090
Loop=1 PID=12090
Loop=2 PID=12090
Loop=3 PID=12090
Loop=3 PID=12090
This is because the while in BASH is loop executed in a subshell. So any changes you do for the variable will not be available once the subshell exits.
From the PID value, we can found the loop are in process, PID=2647 while script itself PID=2620
The same script in KSH environment use same PID=12090 in all cases.
From the PID value, we can found the loop are in process, PID=2647 while script itself PID=2620
The same script in KSH environment use same PID=12090 in all cases.
本文通过示例对比了Bash和Ksh两种Shell环境下变量的作用域差异,指出Bash中循环内的变量更改不会保留到子Shell外部,而Ksh则保持变量更改。演示了不同Shell对变量处理的不同行为。
2094

被折叠的 条评论
为什么被折叠?



