Looping Through Command Output Safely

Su Suriya Ravichandran Updated 06 Dec 2026
13 min read ·Lesson 83 of 205

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).

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Looping Through Command Output Safely and get answers drawn from it.

Signed-in readers only.