Looping Through Command Output Safely
Many scripts need to run a command and then act on each item it prints: each file find reports, each line of a log, each process in a list. Bash offers several ways to connect a command to a loop, and they are not equally safe. Some of them break on spaces, some expand wildcards that were never meant to be expanded, and some silently lose the variables you set inside the loop.
This lesson explains why the obvious approach, for x in $(command), is risky, and then shows the reliable alternatives: while read fed by a redirection, process substitution, here strings, mapfile, and null-separated output from find.
The Obvious Approach and Why It Fails
The first idea of most learners is to put the command inside $(...) and loop over the result. Suppose a folder contains three files: a b.txt, c.txt and d e f.txt:
for f in $(ls *.txt | head -3); do echo "[$f]"; done
Output:
[a]
[b.txt]
[c.txt]
[d]
[e]
[f.txt]
The output of $(...) is a single string. Because the substitution is not quoted, Bash performs word splitting on it (lesson 53) and cuts it at every space, tab and newline. The three file names became six words. The loop has no way to know that a and b.txt belong together.
A second problem is that the words are also subject to filename expansion (lesson 52). Suppose a file pattern.lst contains the text *.txt:
echo '*.txt' > pattern.lst
for w in $(cat pattern.lst); do echo "word: [$w]"; done | head -3
Output:
word: [a b.txt]
word: [c.txt]
word: [d e f.txt]
The text *.txt that the command printed was expanded into the names of the matching files. The loop received something other than what the command produced. Quoting the substitution ("$(cat pattern.lst)") would keep it from splitting, but then the loop would run once with one big string, which is not what we want either.
Rule of thumb: do not use for x in $(command) when the output may contain spaces, wildcard characters or one item per line that must stay intact. It is acceptable only for output you fully control, such as a list of plain numbers.
Reading Line by Line with while read
The reliable pattern is a while loop whose condition is the read command (lessons 31 and 80). The command reads one line at a time, so spaces inside a line are not a problem:
printf 'first line\n indented\nback\\slash\n' > lines.txt
cat lines.txt | while IFS= read -r l; do echo "[$l]"; done
Output:
[first line]
[ indented]
[back\slash]
Two details make this exact. IFS= (an empty value, set only for the read command) stops read from trimming leading and trailing spaces, and -r stops it from treating a backslash as an escape character. Use IFS= read -r whenever lines must be kept exactly as they are.
The Pipe Problem: A Subshell Loses Variables
There is a catch in the example above. In a pipeline such as command | while read ..., each side runs in its own subshell (a child copy of the shell). Anything the loop changes disappears when the pipeline ends:
n=0
printf 'a\nb\nc\n' | while read -r l; do n=$((n+1)); done
echo "n after pipe: $n"
Output:
n after pipe: 0
The loop counted to 3 inside its subshell, but the variable n of the main script was never touched. This is the single most common reason a counter "doesn't work" in a loop that reads command output. There are three ways around it, and each also protects you in other ways.
Process Substitution
The form <(command) runs the command and gives you a file-like name that you can redirect into the loop. Because the loop now reads from a redirection, not a pipe, it stays in the current shell:
n=0
while read -r l; do n=$((n+1)); done < <(printf 'a\nb\nc\n')
echo "n after <(): $n"
Output:
n after <(): 3
The first < redirects input into the loop and the second <(...) is the process substitution (lesson 151). They are separated by a space and are two different operators. This is the form to prefer when the data comes from a command and the loop must change variables.
A Here String
When the output is small and already stored in a variable, a here string (lesson 64) feeds it to the loop without creating a process:
n=0
out=$(printf 'a\nb\nc\n')
while read -r l; do n=$((n+1)); done <<< "$out"
echo "n after here string: $n"
Output:
n after here string: 3
The command substitution stores the whole output in out, and <<< sends it to the loop as input. The loop stays in the main shell. One advantage of this form is that it gives you a place to check whether the command succeeded, which the next section uses.
The lastpipe Option
Bash can also run the last command of a pipeline in the current shell when the option lastpipe is on. This works in scripts, where job control is off:
shopt -s lastpipe
n=0
printf 'a\nb\n' | while read -r l; do n=$((n+1)); done
echo "n with lastpipe: $n"
Output:
n with lastpipe: 2
The option is specific to Bash and changes how every pipeline in the script behaves, so many authors prefer process substitution, which is explicit about what it does.
Capturing Into an Array with mapfile
If you want all lines available at once, for example to know how many there are before the loop starts, mapfile (also called readarray) reads lines straight into an array (lessons 97 to 99):
mapfile -t arr < <(printf 'one\ntwo words\nthree\n')
echo "count=${#arr[@]}"
for item in "${arr[@]}"; do echo "[$item]"; done
Output:
count=3
[one]
[two words]
[three]
The option -t removes the trailing newline from each line. The element two words stays together because the array expansion "${arr[@]}" is quoted, which produces one word per element. mapfile is a Bash feature; Dash has no arrays.
File Names: Why ls Is the Wrong Tool
Parsing the output of ls is one of the classic mistakes, because file names may contain any character except a slash and the null character. That includes spaces and even newlines. Consider a folder with a b.txt, c.txt and a file whose name contains a line break. The file is called line, a newline, then break.txt:
ls | wc -l
n=0; for f in *; do n=$((n+1)); done; echo "glob count: $n"
Output:
4
glob count: 3
There are three files but ls printed four lines, because the file with the newline in its name produced two lines. Any loop that reads lines from ls will treat line and break.txt as two separate files that do not exist. Here are the three loops side by side:
for f in $(ls); do echo "[$f]"; done
echo "--- while read over ls"
ls | while IFS= read -r f; do echo "[$f]"; done
echo "--- glob"
for f in *; do printf '[%s]\n' "$f"; done
Output:
[a]
[b.txt]
[c.txt]
[line]
[break.txt]
--- while read over ls
[a b.txt]
[c.txt]
[line]
[break.txt]
--- glob
[a b.txt]
[c.txt]
[line
break.txt]
Only the glob produced the correct three names. The for loop over $(ls) was wrong in two ways (the space split and the newline split), and the while read version fixed the space but not the newline. To loop over files in a folder, use a glob (lesson 82). To loop over files found in many folders, use find with null separators.
Safe Loops over find Output
The command find prints one path per line by default, which has the same newline problem:
find . -type f | while IFS= read -r f; do printf '[%s]\n' "$f"; done
Output:
[./a b.txt]
[./line]
[break.txt]
[./c.txt]
The file with the newline in its name was split into two bogus paths again. The option -print0 makes find end each path with a null character instead of a newline. A null character cannot be part of a file name, so it is a perfectly safe separator. The read option -d '' makes read use that null character as the end of a record:
find . -type f -print0 | sort -z | while IFS= read -r -d '' f; do printf '[%s]\n' "$f"; done
Output:
[./a b.txt]
[./c.txt]
[./line
break.txt]
All three files are intact, including the one with a newline in its name. The option -z makes sort handle null-separated records. To keep variables, combine the same idea with process substitution and collect the names into an array:
files=()
while IFS= read -r -d '' f; do files+=("$f"); done < <(find . -maxdepth 1 -name '*.txt' -print0 | sort -z)
echo "found ${#files[@]} files"
Output:
found 5 files
This test folder holds five .txt files: the three names from the first example in this lesson, a file called lines.txt, and the file whose name contains a newline. The loop uses += to append each name to the array (lesson 99). Alternatively, mapfile can read the null-separated records directly:
mapfile -d '' -t arr2 < <(find . -maxdepth 1 -name '*.txt' -print0 | sort -z)
echo "mapfile -d count=${#arr2[@]}"
Output:
mapfile -d count=5
The -d '' option of mapfile requires Bash 4.4 or later. Lesson 112 shows the other classic safe pattern, find -print0 | xargs -0.
Fields on Each Line
When each line has several columns, give read several variable names. It splits the line into words, puts each word into a variable, and puts any remaining words into the last variable:
printf 'ana 30\nbob 25\n' | while read -r name age; do echo "$name is $age"; done
Output:
ana is 30
bob is 25
This works well for tools whose output is a table, such as ps, df and uniq -c. For example, counting repeated words:
printf 'b\na\nb\na\nc\n' | sort | uniq -c | while read -r cnt word; do echo "$word appears $cnt time(s)"; done
Output:
a appears 2 time(s)
b appears 2 time(s)
c appears 1 time(s)
The uniq -c command pads the counts with spaces, and the default read splitting removes that padding. Because the loop only prints, the subshell of the pipe causes no harm here.
Checking That the Command Succeeded
When a loop reads from <(command), the status of the command is not visible to the script. The loop sees whatever the command printed before it failed, and the loop itself reports success:
while read -r l; do echo "got $l"; done < <(false; echo after)
echo "status of loop: $?"
Output:
got after
status of loop: 0
Here the command list false; echo after printed one line and the failed false went unnoticed. If a failure must stop the work, capture the output first and test the result of the command substitution (lesson 48). Then feed the loop with a here string:
if out=$(false); then echo ok; else echo "command failed, skip loop"; fi
Output:
command failed, skip loop
In the full pattern, you would run if out=$(some_command); then and put the while read ... <<< "$out" loop inside the then branch. The price is that the whole output is stored in memory before the loop starts, which is fine for modest output but not for gigabytes of data.
The Last Line Without a Newline
The read command reports failure when it reaches the end of the input without finding a newline. If the last line of the data has no newline, read still stores the text but the loop ends before the body can use it. The fix is to run the body also when the variable is not empty:
printf 'one\ntwo' | while IFS= read -r l || [ -n "$l" ]; do echo "[$l]"; done
Output:
[one]
[two]
Without || [ -n "$l" ], the output would have been only [one] (lesson 80 shows this in detail). Output from commands normally ends with a newline, so this matters mostly for data files written by other programs.
A Command Inside the Loop Can Steal the Input
When a loop reads from a file or pipe, that data is the standard input of every command in the loop body. A command that also reads standard input will swallow lines that were meant for the loop. This example uses head -n 1 as a stand-in for any such command (ssh, ffmpeg, cat and others behave this way):
printf 'h1\nh2\nh3\n' > hosts.txt
while IFS= read -r h; do echo "host $h"; head -n 1; done < hosts.txt
Output:
host h1
h2
host h3
The loop never saw h2: the head command read it from the same input and printed it. There are two cures. The first is to redirect the input of the inner command, for example head -n 1 < /dev/null, so it cannot read the loop's data. The second is to give the loop its own file descriptor, with read -u 3 and 3< file:
while IFS= read -r -u 3 h; do echo "host $h"; echo "typed" | head -n 1; done 3< hosts.txt
Output:
host h1
typed
host h2
typed
host h3
typed
The loop now reads from descriptor 3, so the commands in its body keep their own standard input. The same loop with head -n 1 < /dev/null as the inner command printed host h1, host h2 and host h3 with nothing swallowed.
Splitting on Newlines Only
Sometimes you really do want for to receive the whole output, one word per line. The loop can be made to split only on newlines by changing IFS (lesson 53) and switching off filename expansion with set -f:
IFS=$'\n'
set -f
for l in $(printf 'one two\nthree four\n'); do echo "[$l]"; done
set +f
unset IFS
Output:
[one two]
[three four]
Setting IFS to a newline stops splitting on spaces, and set -f stops the shell from expanding wildcards in the result. Remember to restore both afterwards, as done here with set +f and unset IFS. This still cannot handle file names that contain newlines, and the changes affect the rest of the script, so most authors prefer while read or mapfile.
Letting xargs Run the Command
If the real goal is only to run a command once per item, you may not need a loop at all. The xargs program reads items and builds commands from them:
printf 'a\nb c\nd\n' | xargs -I{} echo "item: {}"
Output:
item: a
item: b c
item: d
The option -I{} runs the command once per input line and replaces {} with the whole line, so b c stays together. Lesson 112 covers xargs with find -print0 for file names.
Portability
The while IFS= read -r line loop, redirection from a file and here documents work in every POSIX shell. The other tools from this lesson do not:
#!/bin/sh
printf 'a\nb\n' > l.txt
n=0
while IFS= read -r l; do n=$((n+1)); done < l.txt
echo "n=$n"
Dash prints n=2 for this. Three features fail in Dash: process substitution (Syntax error: redirection unexpected), read -d (Illegal option -d), and mapfile, which does not exist. A pipe into a while loop also runs in a subshell in Dash, so a counter stays 0 there, exactly as in Bash. For sh scripts, read from a file, or write the command output to a temporary file first (lesson 113) and redirect that file into the loop (lessons 188 and 189).