程序1
#!/bin/sh
count=0
cat temp.txt|while read fre
do
count=$(($count+$fre))
done
echo "$count"
exit 1
程序2
#!/bin/sh
count=0
exec 3< temp.txt
while read fre <&3
do
count=$(($count+$fre))
done
echo "$count"
exit 1
程序3
#!/bin/sh
count=0
while read fre
do
count=$(($count+$fre))
done<temp.txt
echo "$count"
exit 1
temp.txt文件
2
2
在运行以上3个程序以后我们会发现
1程序输出结果是0
2,3的输出结果为正确的4
原因是因为程序1使用了管道,管道中的while是在子shell中运行的,并不能返回到父shell中
所以count的值成为了初始化时的值
本文探讨了三种Shell脚本程序处理文件数据的不同方式,并详细分析了为何在使用管道时,变量更新无法在父进程生效的原因。通过具体的代码示例和运行结果对比,帮助读者理解Shell脚本中变量的作用域及正确使用方法。
2054





