The short answer

#

Use a while loop with read, redirect the file into the loop, and set IFS= and -r so each line arrives exactly as written.


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

Why it happens

#

The obvious approach, for line in $(cat file), does not loop over lines at all. The shell splits the output of cat on every space, tab and newline, and then expands any * or ? as file name patterns. A line like hello world becomes two iterations, and a line containing * turns into a list of files in the current directory.

read is the tool designed for this. It reads one line from standard input into a variable. By default, though, it changes the line in two ways:

  • It trims leading and trailing whitespace, because those characters are in IFS, the input field separator. Setting IFS= for just the read command turns that off.
  • It treats a backslash as an escape character, so C:\temp loses its backslash and a backslash at the end of a line joins it to the next one. The -r flag turns that off.

The || [[ -n "$line" ]] part handles files whose last line has no trailing newline. read returns a failure status when it hits the end of the file, even if it did read some text first, so without this check the last line is silently skipped.

How to fix it

#

The standard loop


_10
file="hosts.txt"
_10
_10
while IFS= read -r line || [[ -n "$line" ]]; do
_10
[[ -z "$line" || "$line" == \#* ]] && continue # skip blank lines and comments
_10
echo "Pinging $line"
_10
done < "$file"

The redirection goes after done, so it applies to the whole loop and the file is opened once.

Split each line into fields

Give read several variable names and set IFS to the separator. The last variable gets the rest of the line.


_10
while IFS=, read -r name email role; do
_10
echo "$name has role $role"
_10
done < users.csv

This is fine for simple comma-separated data. It does not understand quoted fields containing commas, so use a real CSV tool for anything more complex.

Read the output of a command

Piping into the loop works, but each part of a pipeline runs in a subshell. Variables set inside the loop are lost when it ends:


_10
count=0
_10
grep ERROR app.log | while IFS= read -r line; do
_10
(( count++ ))
_10
done
_10
echo "$count" # prints 0

Use process substitution instead, which keeps the loop in the current shell:


_10
count=0
_10
while IFS= read -r line; do
_10
(( count++ ))
_10
done < <(grep ERROR app.log)
_10
echo "$count" # prints the real count

Load all lines into an array

In Bash 4 and later, mapfile (also called readarray) reads every line into an array in one go. -t removes the trailing newline from each element.


_10
mapfile -t lines < input.txt
_10
echo "Read ${#lines[@]} lines"
_10
for line in "${lines[@]}"; do
_10
printf '%s\n' "$line"
_10
done

The /bin/bash that ships with macOS is version 3.2, which does not have mapfile. Install a newer Bash with Homebrew, or stick with the while read loop if the script must run there.

Commands inside the loop that read input

Anything inside the loop that reads standard input, such as ssh, ffmpeg or another read, will swallow the rest of the file and the loop stops early. Read the file on a different file descriptor:


_10
while IFS= read -r -u 3 host; do
_10
ssh "$host" uptime
_10
done 3< hosts.txt

For ssh specifically, ssh -n also works.

Common pitfalls

#
  • Using for line in $(cat file). It splits on spaces and expands globs.
  • Forgetting -r, so backslashes disappear.
  • Forgetting IFS=, so indentation is stripped from every line.
  • Losing the last line of a file with no trailing newline.
  • Piping into while and expecting variables to survive the loop.
  • Reading Windows files with CRLF line endings. Each line keeps a trailing carriage return, which breaks comparisons. Strip it with line=${line%$'\r'} inside the loop, or convert the file with dos2unix.
  • Reaching for a Bash loop to process large files. Tools like awk, grep and sed are far faster for line-by-line work on big inputs.
#
file under:
Bash

quick question

Was this resource helpful?