Read file line by line
Reading a file into a bash script on a per-line basis is pretty simple:
1while read -r line; do command "${line}"; done < src.file
here we read a line from stdin and as long as a line was read the line is passed to command as a single command argument.
the -r
option prevents backslash escapes in the line being interpreted.
If you want to prevent leading or trailling whitespace from being removed from the line then add
IFS=
to the line:
1while IFS= read -r line; do command "${line}"; done < src.file
Within scripts
The above is useful when writing something quick on the command line, but in a script it's more customary to write this across multiple lines.
What I tend to do is wrap the while loop within ( )
with the input redirect after the parentheses.
To me this makes it clearer on what the bounds of the script relates to the input.
For example, here we have a script which writes the content of a file to stdout but adds line numbers to the output:
When run against itself: