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.
_10while IFS= read -r line || [[ -n "$line" ]]; do_10 printf '%s\n' "$line"_10done < 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. SettingIFS=for just thereadcommand turns that off. - It treats a backslash as an escape character, so
C:\temploses its backslash and a backslash at the end of a line joins it to the next one. The-rflag 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
_10file="hosts.txt"_10_10while IFS= read -r line || [[ -n "$line" ]]; do_10 [[ -z "$line" || "$line" == \#* ]] && continue # skip blank lines and comments_10 echo "Pinging $line"_10done < "$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.
_10while IFS=, read -r name email role; do_10 echo "$name has role $role"_10done < 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:
_10count=0_10grep ERROR app.log | while IFS= read -r line; do_10 (( count++ ))_10done_10echo "$count" # prints 0
Use process substitution instead, which keeps the loop in the current shell:
_10count=0_10while IFS= read -r line; do_10 (( count++ ))_10done < <(grep ERROR app.log)_10echo "$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.
_10mapfile -t lines < input.txt_10echo "Read ${#lines[@]} lines"_10for line in "${lines[@]}"; do_10 printf '%s\n' "$line"_10done
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:
_10while IFS= read -r -u 3 host; do_10 ssh "$host" uptime_10done 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
whileand 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 withdos2unix. - Reaching for a Bash loop to process large files. Tools like
awk,grepandsedare far faster for line-by-line work on big inputs.
Related reading
#Bashquick question
Was this resource helpful?