title: Difference between `exec n<&0 < file` and `exec n<file` commands and some general questions regarding exec command
body: <p>As I am a newbie in shell scripting, <code>exec</code> command always confuses me and while exploring this topic with <code>while</code> loop had triggered following 4 questions:</p>
  
  <ol>
  <li><p>What is the difference between the below syntax 1 and 2</p>
  
  <p>syntax 1:</p>
  
  <pre><code>while read LINE
  do
  : # manipulate file here
  done &lt; file
  </code></pre>
  
  <p>syntax 2:</p>
  
  <pre><code>exec n&lt;&amp;0 &lt; file
   while read LINE
   do
     : # manipulate file here
   done
  exec 0&lt;&amp;n n&lt;&amp;-
  </code></pre></li>
  <li><p>Kindly elaborate the operation of <code>exec n&lt;&amp;0 &lt; file</code> lucidly </p></li>
  <li><p>Is this <code>exec n&lt;&amp;0 &lt; file</code> command equivalent to <code>exec n&lt;file</code> ? (if not then what's the difference between two?)</p></li>
  <li><p>I had read some where that in <em>Bourne shell and older versions of ksh</em>, <strong>a problem with the <code>while</code> loop is that it is executed in a subshell</strong>. This means that any changes to the script environment,such as exporting variables and changing the current working directory, might not be present after the <code>while</code> loop completes.
  As an example, consider the following script:</p>
  
  <pre><code>#!/bin/sh
  if [ -f “$1” ] ; then
   i=0
    while read LINE
    do
     i=`expr $i + 1`
    done &lt; “$1”
   echo $i
  fi
  </code></pre></li>
  </ol>
  
  <p>This script tries to count the number of lines in the file specified to it as an argument.</p>
  
  <p>On executing this script on the file</p>
  
  <pre><code>$ cat dirs.txt
  /tmp
  /usr/local
  /opt/bin
  /var
  </code></pre>
  
  <p>can produce the following incorrect result:
  0</p>
  
  <p>Although you are incrementing the value of $i using the command
  i=<code>expr $i + 1</code>
  when the while loop completes, the value of $i is not preserved. </p>
  
  <p>In this case, you need to <strong><em>change a variable’s value inside the <code>while</code> loop and then use that value outside the loop.</em></strong> </p>
  
  <p>One way to solve this problem is to redirect STDIN prior to entering the loop and then restore STDIN after the loop completes. </p>
  
  <p>The basic syntax is</p>
  
  <p><code>exec n&lt;&amp;0 &lt; file
  while read LINE
  do
  : # manipulate file here
  done
  exec 0&lt;&amp;n n&lt;&amp;-</code></p>
  
  <p>My question here is:</p>
  
  <p>In <em>Bourne shell and older versions of ksh</em>,<em>ALTHOUGH <code>WHILE</code> LOOP IS EXECUTED IN SUBSHELL</em>, how this <code>exec</code> command here helps in retaining variable value even after <code>while</code> loop completion i.e. how does here <code>exec</code> command accomplishes the task <strong><em>change a variable’s value inside the <code>while</code> loop and then use that value outside the loop.</em></strong></p>