为什么我的Bash计数器在while循环后重置
发布时间:2020-12-15 18:51:20 所属栏目:安全 来源:网络整理
导读:我有一个 Bash脚本,我想计算在循环一个文件时做了多少事情.该计数似乎在循环中工作,但在变量似乎重置之后. nKeys=0cat afile | while read -r linedo #...do stuff let nKeys=nKeys+1 # this will print 1,2,...,etc as expected echo Done entry $nKeysdone
我有一个
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 上面的输出是单独的输出: Done entry 1 Done entry 2 Finished writing /blah,0 keys 我想要的输出是: Done entry 1 Done entry 2 Finished writing /blah,2 keys 我不太确定为什么nKeys在循环后为0 :(我认为这是一些基本的东西,但如果我能发现它,尽管看到了http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html和其他资源. 手指交叉别人可以看着它,去“好吧,你必须…”!
在刚刚发布的Bash 4.2中,您可以这样做,以防止创建一个subshel??l:
shopt -s lastpipe 另外,正如你可能会在Ignacio提供的链接中看到的,你有一个Useless Use of while read -r line do ... done < afile (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |