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?
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
With < You are basically saying to send the contents of "file" to the while loop.
for complete docs: Bash Redirections
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With