variable in while loop between ksh vs. bash

本文通过示例对比了Bash和Ksh两种Shell环境下变量的作用域差异,指出Bash中循环内的变量更改不会保留到子Shell外部,而Ksh则保持变量更改。演示了不同Shell对变量处理的不同行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值