Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

done < {filename} in the while loop

Tags:

bash

Wanted to ask about something in bash.

When using the while loop I've seen use of a last line that looks like this:

done < {filename}

Seen for example when reading a file.

while read line; do
    echo $line
done < file

I guess it is being checked against some boolean statement but "file" does not get changed in any way.

What does this exactly mean?

like image 699
AlphaBeta Avatar asked Dec 10 '22 18:12

AlphaBeta


2 Answers

while read line; do
    echo $line
done < file

This is not bash specific. It redirects the file to the standard input of the loop. In the case you show, this goes to the read command. So what's wrong with this?

while read line < file    # WRONG!
do
    echo $line
done 

This will give an infinite loop. Why? Because read line < file reads the first line of file. So what? Well it does that on each iteration of the loop, continually reading the first line of the file. This is because it actually reads the first line of the file and then closes the file, the file position is not retained.

The loop will only exit when read is unsuccessful (returns non-zero), which usually is when it hits End-Of-File (EOF). In the wrong example it will never hit EOF, it successfully reads the first line each time, so we get an infinite loop.

The syntax can also be used with functions (although you don't see it often):

myfunc() {
    while read line; do
        echo $line
    done
} < file

Finally, to check that you understand this, what will happen here?

while read line 
do
    echo "x" $line
    cat
done < file
like image 62
cdarke Avatar answered Dec 30 '22 22:12

cdarke


With < You are basically saying to send the contents of "file" to the while loop.

for complete docs: Bash Redirections

like image 21
Daniel B. Avatar answered Dec 30 '22 22:12

Daniel B.