title: Shell - Variable loses value after loop
body: <p>I'm trying to count the occurrence of a word in a file which contains one word per line (using egrep was forbidden). I managed to find a solution, however I've stumbled upon a pretty strange thing, which I'd like some explanation as to why it happens like this.</p>
  
  <p>My "count" variable has value of 0 after the loop, but it gets incremented correctly during the loop.</p>
  
  <p>Here's my code:</p>
  
  <pre><code>for var in "$@" 
  do
      count=0
      cat $1 | while read line ; do
          if [ $line = $var ]; then
              count=$((count + 1))
              echo "$var found $count times"
          fi
      done    
      echo $count
  done
  </code></pre>
  
  <p>My output is:</p>
  
  <pre><code>yes found 0 times
  yes found 1 times
  yes found 2 times
  0 - This is from the echo $count, which I find it very odd to be zero, since it got incremented to 3 during the loop.
  </code></pre>