Search code examples
bashloopsshio-redirection

I/O redirection in a while loop


What is the difference between the following two blocks of code in reading the content of a file?

while read i; do 
    echo $i
done < ${filename}
while read i < ${filename}; do 
    echo $i
done 

Solution

  • You can write it that way, but it always reads the first line.

    Think of the while loop like this:

    1. In the first case:
      1. Connect the file to stdin
      2. Read until a newline
      3. Loop (read the next line)
      4. Disconnect the file
    2. In the second case:
      1. Connect the file to stdin
      2. Read until a newline
      3. Disconnect the file
      4. Loop (reconnect the file, read a line, disconnect the file)