title: Why does my Bash counter reset after while loop
body: <p>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. </p>
  
  <pre><code>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
  </code></pre>
  
  <p>The output of the above is something alone the lines of:</p>
  
  <pre>
  Done entry 1
  Done entry 2
  Finished writing /blah, 0 keys
  </pre>
  
  <p>The output I want is:</p>
  
  <pre>
  Done entry 1
  Done entry 2
  Finished writing /blah, 2 keys
  </pre>
  
  <p>I am not quite sure why nKeys is 0 after the loop :( I assume it's something basic but damned if I can spot it despite looking at <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html">http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html</a> and other resources. </p>
  
  <p>Fingers crossed someone else can look at it and go "well duh! You have to ..."!</p>