先上代码
#!/bin/bash
cnt=0
cat /data/test_file.txt | while read lines #方式一
# while [ $cnt -lt 5 ] #方式二
do
cnt=$[$cnt+1]
echo "cnt="$cnt
done
echo "合计$cnt条"
输出
cnt=1
cnt=2
cnt=3
cnt=4
合计0条
结果让我很懵逼,把cat /data/test_file.txt | while read lines 换成 while [ $cnt -lt 5 ]又试了试,输出”合计10条“。
分析
while 循环本身没问题,那么就是cat xxx|while 的管道有问题。查了半天,当启用管道时,会生成一个subshell,计数器在子shell中计数,但是变量循环体外的主shell并没有被修改。
解决办法
不用管道,采取重定向方式
#!/bin/bash
cnt=0
while read lines
do
cnt=$[$cnt+1]
echo "cnt="$cnt
done </data/test_file.txt |
echo "合计$cnt条"
输出
cnt=1
cnt=2
cnt=3
cnt=4
合计4条