为什么while循环后我的Bash计数器会重置

我有一个Bash脚本,我想在其中计算在循环文件时完成了多少操作。计数似乎在循环内起作用,但在此之后,变量似乎已重置。


nKeys=0

cat afile | while read -r line

do

  #...do stuff

  let nKeys=nKeys+1

  # this will print 1,2,..., etc as expected

  echo Done entry $nKeys

done

# PROBLEM: this always prints "... 0 keys"

echo Finished writing $destFile, $nKeys keys

上面的输出仅是以下几行的内容:


完成输入1

完成输入2

完成写/ blah,0键

我想要的输出是:


完成输入1

完成输入2

完成写/ blah,2键

我不太确定为什么循环后nKeys为0 :(我认为这是基本的东西,但是尽管我看了http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html,但还是能认出它,但该死的和其他资源。


手指交叉着别人可以看着它,然后走开,“嗯!你必须……”!


斯蒂芬大帝
浏览 725回答 3
3回答

MMTTMM

在刚刚发布的Bash 4.2中,您可以执行以下操作以防止创建子外壳:shopt -s lastpipe另外,您可能会在Ignacio提供的链接中看到,您对的无用cat。while read -r linedo&nbsp; &nbsp; ...done < afile

慕的地10843

如已接受的答案中所述,这是因为管道产生了单独的子流程。为避免这种情况,command grouping一直是我的最佳选择。也就是说,在子外壳中的管道之后进行所有操作。nKeys=0cat afile |&nbsp;{&nbsp; while read -r line&nbsp; do&nbsp; &nbsp; #...do stuff&nbsp; &nbsp; let nKeys=nKeys+1&nbsp; &nbsp; # this will print 1,2,..., etc as expected&nbsp; &nbsp; echo Done entry $nKeys&nbsp; done&nbsp; # PROBLEM: this always prints "... 0 keys"&nbsp; echo Finished writing $destFile, $nKeys keys}现在它将报告$nKeys“正确” 的值(即您希望的值)。
打开App,查看更多内容
随时随地看视频慕课网APP