为什么while循环之后做我的Bash计数器复位 [英] Why does my Bash counter reset after while loop

查看:110
本文介绍了为什么while循环之后做我的Bash计数器复位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Bash脚本,我想指望有多少事做完了通过文件循环时。伯爵似乎在循环中工作,但之后该变量似乎复位。

I have a Bash script where I want to count how many things were done when looping through a file. The count seems to work within the loop but after it the variable seems reset.

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

以上的输出是一些单独的行:

The output of the above is something alone the lines of:


Done entry 1
Done entry 2
Finished writing /blah, 0 keys

我想要的输出是:

The output I want is:


Done entry 1
Done entry 2
Finished writing /blah, 2 keys

我不明白为什么在循环后nKeys是0 :(我以为这是一些基本的东西,但如果我可以,尽管在看<一个发现它该死href=\"http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html\">http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html和其他资源。

手指交叉别人可以看着它,走以及咄!你要......!

Fingers crossed someone else can look at it and go "well duh! You have to ..."!

推荐答案

BASH FAQ条目#24:我设置的变量在一个循环。为什么他们突然消失循环终止后?或者说,我为什么不能管数据读?

这篇关于为什么while循环之后做我的Bash计数器复位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆