The obvious way to loop over a file in Bash loses leading spaces, eats backslashes, and skips the last line if the file does not end with a newline. None of that produces an error. The correct loop is one line longer and every piece of it is there for a reason. The output below is from Bash 5.2.21, run against a four-line test file built to trip each failure.
The test file and the naive loop
Four lines, three traps
The file has a line that starts with two spaces, a line with backslashes in it, a plain line, and a last line with no newline after it. cat -A marks each line ending with a $:
indented line$
back\slash and tab\there$
plain line$
last line no newline
The loop most people write first:
while read line; do
echo "[$line]"
done < f.txt
[indented line]
[backslash and tabthere]
[plain line]
Three things went wrong in three lines of output. The leading spaces are gone. Both backslashes are gone. The fourth line never appeared.

The loop that works
while IFS= read -r line || [[ -n $line ]]; do
echo "[$line]"
done < f.txt
[ indented line]
[back\slash and tab\there]
[plain line]
[last line no newline]
All four lines, byte for byte. The three additions each fix one of the three losses.
IFS= keeps the whitespace
The Bash manual describes read as taking one line from standard input and then splitting it into words using the characters in the IFS variable, under the same rules the shell uses for expansion. With the default IFS of space, tab and newline, that splitting strips whitespace from both ends of the line before it lands in the variable.
Writing IFS= in front of read sets the variable to empty for that one command. Nothing to split on, nothing trimmed. Because the assignment is a prefix to the command, it does not change IFS for the rest of the script.
-r keeps the backslashes
By default, the manual says, the backslash removes any special meaning from the next character read and is used for line continuation. That is why \s became s and \t became t above. The -r option switches it off: with it, in the manual’s words, “backslash does not act as an escape character. The backslash is considered to be part of the line.”
There is almost never a reason to want the default. A Windows path, a regular expression or a LaTeX line read without -r arrives damaged.
|| [[ -n $line ]] catches the last line
read returns a non-zero status when it hits end of file, which is what ends the loop. On a file whose last line has no trailing newline, read fills the variable with that final text and returns failure in the same call. The loop sees the failure and stops with the data still sitting in $line, unprocessed.
The extra test says: keep going if read succeeded, or if it failed but left something in the variable. wc -l on the test file reports 3 for the same reason. It counts newline characters, and there are three.
Why a for loop is the wrong tool
Words, not lines
for w in $(cat f.txt); do echo "[$w]"; done
[indented]
[line]
[back\slash]
[and]
[tab\there]
...
The command substitution hands the whole file to the shell as one string, and the shell splits it on every space, tab and newline. The loop runs once per word. It also loads the entire file into memory first, and any word that contains * or ? gets expanded against the files in the current directory.
Changing IFS to a newline for the for loop fixes the splitting and leaves the other two problems. The while read form has none of them.

The pipe that loses variables
A counter that stays at zero
Counting lines with a pipe into the loop:
n=0
cat f.txt | while IFS= read -r line; do n=$((n+1)); done
echo "n=$n"
n=0
The loop ran three times and n is zero afterwards. The manual explains it in one sentence: “Each command in a multi-command pipeline, where pipes are created, is executed in its own subshell, which is a separate process.” The while loop incremented a copy of n inside that subshell, and the copy vanished when the pipeline ended.
Two fixes
Redirecting the file into the loop keeps everything in the current shell:
n=0
while IFS= read -r line; do n=$((n+1)); done < f.txt
echo "n=$n" # n=3
When the input comes from a command instead of a file, process substitution does the same job. Note the space between the two < characters:
n=0
while IFS= read -r line; do n=$((n+1)); done < <(grep -v plain f.txt)
echo "n=$n" # n=3
Bash also has a lastpipe option. Per the manual, when it is set and job control is not active, the shell runs the last command of a pipeline in the current shell environment. That makes the piped version work in scripts, though not at an interactive prompt, where job control is on.
When something inside the loop eats the input
One iteration and out
The loop reads from standard input. So does every command inside it, unless told otherwise. Here cat stands in for any program that reads stdin, such as ssh or ffmpeg:
while IFS= read -r h; do
echo "host $h"
cat > /dev/null
done < hosts.txt
host one
The file has three lines. read took the first, cat swallowed the other two, and on the next pass read found nothing left.
Give the loop its own file descriptor
The -u option tells read to take input from a numbered file descriptor instead of standard input. Opening the file on descriptor 3 leaves descriptor 0 alone for the commands in the body:
while IFS= read -r -u 3 h; do
echo "host $h"
cat > /dev/null
done 3< hosts.txt
host one
host two
host three
The other common fix is to redirect the inner command’s input from /dev/null. For ssh specifically, its -n flag does that.

Splitting each line into fields
Put IFS to work
The same word splitting that causes trouble can be used on purpose. Setting IFS to a delimiter and giving read several variable names splits each line into columns. Two lines in the format of /etc/passwd:
while IFS=: read -r user _ uid _ _ home shell; do
echo "$user uid=$uid home=$home shell=$shell"
done < pw.txt
root uid=0 home=/root shell=/bin/bash
www-data uid=33 home=/var/www shell=/usr/sbin/nologin
The underscore is an ordinary variable name used as a throwaway for unwanted columns. The manual spells out the edge cases: if there are more words than names, the remaining words and the delimiters between them all go to the last name, and if there are fewer, the leftover names are assigned empty values.
Skipping comments and blank lines
while IFS= read -r line; do
[[ -z $line || $line =~ ^[[:space:]]*# ]] && continue
echo "use: $line"
done < conf.txt
Against a five-line file with a comment, a blank line and an indented comment, that printed only the two real entries.
Windows line endings
A file saved on Windows ends each line with a carriage return before the newline, and read keeps it. Piped through cat -A, a line read from such a file shows as [alpha^M]. One parameter expansion inside the loop removes it:
line=${line%$'\r'}
mapfile, and when not to loop at all
The whole file into an array
When every line is needed at once, mapfile (also spelled readarray) reads lines from standard input into an indexed array, MAPFILE by default. The -t option removes the trailing newline from each element.
mapfile -t lines < f.txt
echo "count=${#lines[@]}"
echo "first=[${lines[0]}] last=[${lines[-1]}]"
count=4
first=[ indented line] last=[last line no newline]
No IFS=, no -r, and it picked up the unterminated last line without help. Other options skip the first lines (-s), stop after a count (-n), or split on a different delimiter (-d).
The speed ceiling
A shell loop runs one builtin call per line, and that has a cost. On a file of 200,000 short lines, an empty while read loop took 0.59 seconds. awk (mawk 1.3.4) counted the same lines in 0.006 seconds, roughly a hundred times faster.
That ratio is from one machine and will move around, but the direction will not. A while read loop is the right tool when each line triggers a command: a host to connect to, a file to convert, a row to act on. When the work is transforming the text itself, counting, summing a column, rewriting fields, the job belongs to awk, sed or grep, which read the file once and never start a shell command per line.
Sources
- GNU Bash Reference Manual (single-page edition): the
readandmapfilebuiltins, “Pipelines,” and thelastpipeshell option: https://www.gnu.org/software/bash/manual/bash.html
