title: A variable modified inside a while loop is not remembered
body: <p>In the following program, if I set the variable <code>$foo</code> to the value 1 inside the first <code>if</code> statement, it works in the sense that its value is remembered after the if statement. However, when I set the same variable to the value 2 inside an <code>if</code> which is inside a <code>while</code> statement, it's forgotten after the <code>while</code> loop. It's behaving like I'm using some sort of copy of the variable <code>$foo</code> inside the <code>while</code> loop and I am modifying only that particular copy. Here's a complete test program:</p>
  
  <pre><code>#!/bin/bash
  
  set -e
  set -u 
  foo=0
  bar="hello"  
  if [[ "$bar" == "hello" ]]
  then
      foo=1
      echo "Setting \$foo to 1: $foo"
  fi
  
  echo "Variable \$foo after if statement: $foo"   
  lines="first line\nsecond line\nthird line" 
  echo -e $lines | while read line
  do
      if [[ "$line" == "second line" ]]
      then
      foo=2
      echo "Variable \$foo updated to $foo inside if inside while loop"
      fi
      echo "Value of \$foo in while loop body: $foo"
  done
  
  echo "Variable \$foo after while loop: $foo"
  
  # Output:
  # $ ./testbash.sh
  # Setting $foo to 1: 1
  # Variable $foo after if statement: 1
  # Value of $foo in while loop body: 1
  # Variable $foo updated to 2 inside if inside while loop
  # Value of $foo in while loop body: 2
  # Value of $foo in while loop body: 2
  # Variable $foo after while loop: 1
  
  # bash --version
  # GNU bash, version 4.1.10(4)-release (i686-pc-cygwin)
  </code></pre>