Reading Files Line by Line
Many scripts process a file one line at a time: a list of servers to check, a configuration file to parse, a log to scan, a list of users to create. Bash does this with a while loop around the read builtin, with the file redirected into the loop:
while IFS= read -r line; do
printf '[%s]\n' "$line"
done < notes.txt
Each pass of the loop reads one line into the variable line. When read reaches the end of the file it returns a non-zero status, and the loop stops. This lesson explains each part of that line, shows why the obvious alternatives go wrong, and covers the situations that need extra care.
The Sample File
notes.txt contains five lines, including leading spaces, a backslash and an empty line:
printf '%s\n' 'first line' ' indented line' 'back\slash' '' 'last line' > notes.txt
The loop above prints every line exactly as stored. The brackets show where each value starts and ends:
[first line]
[ indented line]
[back\slash]
[]
[last line]
Understanding Each Part
while ... done < file
The redirection < notes.txt after done connects the file to the standard input of the whole loop (lesson 58). Every read inside the loop continues from where the previous one stopped, so the loop walks through the file from top to bottom. The file is opened once, before the first pass.
read returns status 0 when it reads a line and status 1 at the end of the input. while runs its body as long as the condition command succeeds (lesson 80), so the loop ends naturally after the last line.
read -r
Without -r, read treats a backslash as an escape character: it removes the backslash and joins a line that ends in