Browse topics

Reading input line by line with while read

Version
5.3
Review
Draft

Summary#

Pair while with IFS= read -r line to process one text line at a time. An empty IFS keeps leading and trailing whitespace, and -r keeps backslashes. At end of input, read returns a nonzero status even if it assigned the last line without a newline.

Syntax#

bash
while IFS= read -r line || [[ -n $line ]]; do
  printf '%s\n' "$line"
done < input.txt

The extra test keeps a nonempty final line when the input lacks a trailing newline. Use done < <(producer) to read a command’s output through process substitution.

Example#

The first line contains spaces at both ends and a backslash. The second line has no final newline. The counter remains available after the loop.

bash
count=0
while IFS= read -r line || [[ -n $line ]]; do
  printf '<%s>\n' "$line"
  count=$((count + 1))
done < <(printf '%s\n%s' '  archive\inbox  ' 'last line')

printf 'lines processed: %d\n' "$count"

Expected output#

Text
<  archive\inbox  >
<last line>
lines processed: 2

Common mistakes#

Piping into while normally runs the loop in a subshell, so updates to a counter are lost to the caller. Redirect input from a file or use process substitution to keep the loop in the current shell. A command in the loop that also reads standard input can consume later lines. If it needs no input, redirect that command from /dev/null.

Version applicability#

The complete example runs on Bash 3.2 in default Bash mode. Process substitution requires a host with /dev/fd support or named pipes. Plain input redirection works without process substitution.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0