In a very short terms, <
redirects file specified to the right of the <
symbol into stdin
stream of whatever command or group of commands you're executing.
The while read -r line; do...done < input.txt
is standard way to read a file line by line. While, of course, $SOME_VAR
doesn't have to be text file - can be named pipe among other things - this is the usual way and is used to avoid problems with word splitting in shell.
Often new to shell scripting think they can do something like for line in $(cat file.txt)
but if each line has multiple words on it separated by spaces, the for loop will be processing each word instead of each line. Something like this:
$ for i in $(cat input.txt); do echo "$i" ; done
one
two
three
four
That's not good. By contrast, while loop lets you process whole line without issues.
$ while read -r line; do echo "$line" ;done < input.txt
one two
three four
You might be wondering why not just use cat | while read -r line...
, but that's extra process and useless use of cat.
Redirection into stdin stream of a loop can be done with other things as well. If you are using bash
that supports <<<
, you could send a string literal of text to your while loop.
while read -r line;do
# do something with line
done <<< "Hello World"
A redundant example ? Yes, but proves the point that such syntax is more about redirecting input to while loop.
See also: