Process Substitution with <(...) and >(...)

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

Many commands only accept file names as arguments. diff compares two files, comm compares two sorted files, paste joins files side by side. But the data you want to give them often comes from a command, not from a file on disk: the sorted contents of a file, the output of ls in two folders, a list fetched with curl. Process substitution bridges this gap. It runs a command and hands its output to another command as if it were a file.

Bash has two forms:

  • <(command) runs command and is replaced by a file name. Reading that file gives you the command's output.
  • >(command) runs command and is replaced by a file name. Writing to that file sends data to the command's input.
diff <(sort a.txt) <(sort c.txt) && echo "same lines, different order"

Here diff receives two file names. Behind each one is a running sort. No temporary files are created and nothing needs cleaning up afterwards.

Process substitution is a Bash feature (also available in Zsh and ksh), not part of the POSIX shell standard. A script that uses it must run under Bash, so it needs the #!/usr/bin/env bash shebang (lesson 26). Running the same line with sh on Debian or Ubuntu (where sh is dash) fails:

$ sh -c 'echo <(true)'
sh: 1: Syntax error: "(" unexpected

Understanding the Concept

Normally data flows between commands through a pipe (lesson 61): cmd1 | cmd2 connects the standard output of cmd1 to the standard input of cmd2. A pipe has one important limit: a command has only one standard input. You cannot pipe two different streams into diff.

Process substitution solves this by giving each stream its own name. The command on the receiving end does not know or care that the "file" is really another process. It opens the name, reads from it, and closes it, exactly as it would with a regular file.

ToolData travels asHow many streamsNeeds cleanup
Pipe a | bstandard input of boneno
Temporary file (mktemp)a real file on diskas many as you createyes (lesson 124)
Process substitutiona file name pointing to a pipeas many as you writeno

How It Works

When Bash sees <(command), it does three things before running the outer command:

  1. It creates a pipe.
  2. It starts command in the background with its standard output connected to the write end of that pipe.
  3. It replaces the whole <(command) text with a file name that refers to the read end of the pipe.

On Linux the file name is a path under /dev/fd/, a special folder in which each entry is an open file descriptor of the current process (lesson 56). You can see the name by printing it:

echo <(true)
/dev/fd/63

ls -l shows that the "file" is really a pipe:

ls -l <(true) | awk '{print $1, $NF}'
lr-x------ pipe:[2220]

The permissions start with l (a symbolic link) and the target is pipe:[2220], an unnamed pipe with an internal number. On systems without /dev/fd, Bash uses a named pipe (FIFO) in a temporary folder instead; the idea is the same.

>(command) works in the opposite direction: the background command reads from the pipe, and the file name refers to the write end.

Two consequences follow from this design:

  • The data can only be read once, from start to end. A pipe is a stream, not a stored file. Programs that need to jump back and forth in a file (seek) or read it twice cannot use a process substitution. Most text tools (diff, comm, paste, grep -f, while read) read straight through and work well.
  • The command runs at the same time as the outer command. It is a separate process, just like each part of a pipeline.

Syntax

<(list)     the output of list, readable as a file
>(list)     the input of list, writable as a file

There must be no space between < or > and the opening parenthesis. < (sort a.txt) is a syntax error because Bash reads it as input redirection followed by a subshell.

list can be any command or group of commands, including pipelines:

wc -l <(cat a.txt b.txt)
6 /dev/fd/63

wc printed the line count and the "file name" it was given, which shows clearly that it received a path.

Basic Example: Comparing Command Output with diff

Two files contain the same names in a different order:

printf 'alice\nbob\ncarol\n' > a.txt
printf 'bob\ncarol\ndave\n'  > b.txt
printf 'carol\nalice\nbob\n' > c.txt

Comparing a.txt and c.txt directly with diff would report differences, because the order differs. Sorting both first answers the real question, "do they contain the same lines?":

diff <(sort a.txt) <(sort c.txt) && echo same
diff <(sort a.txt) <(sort b.txt); echo "status $?"
same
1d0
< alice
3a3
> dave
status 1

Understanding the Example

  • Bash started two sort processes and replaced each <(sort ...) with a /dev/fd/... path.
  • diff opened both paths and read the sorted lines.
  • For a.txt and c.txt, the sorted lines match, so diff printed nothing and exited with status 0, which triggered && echo same.
  • For a.txt and b.txt, diff reported that alice appears only in the first list (1d0, "delete line 1") and dave only in the second (3a3, "add after line 3"). It exited with status 1, which is how diff signals "different".

Without process substitution, you would need two temporary files, two sort commands writing to them, the diff, and a cleanup step.

Comparing Sorted Lists with comm

comm compares two sorted files and prints three columns: lines only in the first, lines only in the second, and lines in both. Options -1, -2 and -3 hide the matching column. Process substitution makes comm practical, because the input is almost never already sorted:

echo "--- in both"
comm -12 <(sort a.txt) <(sort b.txt)
echo "--- in one but not the other"
comm -3 <(sort a.txt) <(sort b.txt)
--- in both
bob
carol
--- in one but not the other
alice
	dave

In the second output, alice is in column 1 (only in a.txt) and dave is indented by a tab, which puts it in column 2 (only in b.txt).

Reading Command Output in a Loop Without Losing Variables

This is one of the most valuable uses of process substitution in scripts. A loop that reads from a pipe runs in a subshell in Bash, because every part of a pipeline runs in its own process. Variables changed inside the loop are lost when the subshell ends:

count=0
printf 'x\ny\nz\n' | while read -r line; do
    count=$((count + 1))
done
echo "pipe count=$count"
pipe count=0

The loop counted three lines, but it counted them in a child process, and the parent's count never changed. Moving the command into a process substitution and redirecting it into the loop with < keeps the loop in the current shell:

count=0
while read -r line; do
    count=$((count + 1))
done < <(printf 'x\ny\nz\n')
echo "ps count=$count"
ps count=3

Notice the two < characters separated by a space. The first is ordinary input redirection (lesson 58); the second is part of <(...). Read it as "redirect input from the file named <(printf ...)".

The same technique works with IFS and multiple fields (lesson 114):

total=0
while read -r n; do
    (( total += n ))
done < <(printf '5\n10\n20\n')
echo "total=$total"

while IFS=: read -r user shell; do
    echo "$user uses $shell"
done < <(printf 'root:/bin/bash\nana:/bin/zsh\n')
total=35
root uses /bin/bash
ana uses /bin/zsh

Bash also offers shopt -s lastpipe (lesson 149), which runs the last command of a pipeline in the current shell. It only works when job control is off, which is the case in scripts but not in an interactive terminal, so done < <(...) is the more predictable choice.

Filling an Array with mapfile

mapfile (also called readarray) reads lines into an indexed array (lesson 97). It must run in the current shell for the array to survive, which makes it a natural partner for process substitution:

mapfile -t users < <(sort c.txt)
declare -p users
declare -a users=([0]="alice" [1]="bob" [2]="carol")

-t removes the trailing newline from each line. declare -p prints the array exactly as Bash stores it.

Combining Several Command Outputs

Commands that accept several files can take several process substitutions. paste joins files line by line:

paste -d, <(printf '1\n2\n3\n') <(printf 'a\nb\nc\n')
paste <(cut -c1 a.txt) a.txt
1,a
2,b
3,c
a	alice
b	bob
c	carol

The second command mixes a process substitution with an ordinary file: the first column is the first letter of each name, produced by cut.

grep -f FILE reads its patterns from a file. With -F (fixed strings) and -x (whole line), it prints lines of one list that appear in another, and the pattern list can come from any command:

grep -Fxf <(printf 'bob\ndave\n') a.txt
bob

Output Process Substitution with >(...)

>(command) gives you a file name that feeds a command. Its most common partner is tee (lesson 62), which copies its input to several files. With output process substitution, each "file" can be a different processing command:

echo "hello world" | tee >(tr a-z A-Z > upper.txt) >(wc -c > count.txt) > /dev/null
sleep 0.3
cat upper.txt count.txt
HELLO WORLD
12

One input line went to two consumers at once: tr wrote an upper-case copy and wc -c counted the bytes (11 characters plus the newline). > /dev/null discarded tee's own copy on standard output.

The sleep is there for a reason. The commands inside >(...) run in the background, and Bash does not wait for them before moving on to the next line. Without a pause, cat might run before tr and wc have finished writing. In a script, the reliable way to wait for the last process substitution is wait $!, because Bash (since version 4.4) sets $! to its process ID (lesson 139):

echo "data" > >(sleep 0.2; tr a-z A-Z > late.txt)
wait $!
cat late.txt
DATA

Processing Standard Error Separately

Output process substitution also works with redirections of a specific file descriptor. This example adds a prefix to every error line while normal output passes through unchanged:

{ echo "info line"; echo "error line" >&2; } 2> >(sed 's/^/[ERR] /' >&2)
info line
[ERR] error line

2> sends standard error into the sed process, and >&2 inside makes sed write its result back to standard error, so the separation of the two streams is preserved. A pipe could not do this, because | only carries standard output.

Exit Status and Errors

The exit status of a line that uses process substitution is the status of the outer command. A failure inside <(...) is not reported:

cat <(false); echo "cat status $?"
cat status 0

false failed, but cat successfully read an empty stream, so the status is 0. Even set -o pipefail (lesson 120) does not change this, because a process substitution is not part of a pipeline. When the inner command's success matters (for example, a download that might fail), either check its output (an empty result is often a good sign of failure) or run it separately first, save its output in a variable or a temporary file, and check $?.

A Complete Example: Comparing Two Folders

compare-dirs.sh compares two folders, for example two versions of a website, and reports files that exist only in one of them and files whose contents changed. It uses process substitution throughout: comm compares two generated file lists, join combines two generated checksum lists, and mapfile stores each result in an array without losing it in a subshell.

#!/usr/bin/env bash
# compare-dirs.sh: compare the files in two folders by name and content
# usage: compare-dirs.sh OLD_DIR NEW_DIR
set -uo pipefail

if (( $# != 2 )); then
    echo "usage: ${0##*/} OLD_DIR NEW_DIR" >&2
    exit 2
fi
old=$1 new=$2
for d in "$old" "$new"; do
    [[ -d $d ]] || { echo "${0##*/}: not a folder: $d" >&2; exit 2; }
done

# list_files DIR: relative paths of all regular files, sorted
list_files() {
    (cd -- "$1" && find . -type f -print | sed 's|^\./||' | LC_ALL=C sort)
}

# checksums DIR: "path<TAB>sha256" for every file, sorted by path
checksums() {
    (cd -- "$1" && find . -type f -print0 | LC_ALL=C sort -z |
        xargs -0 -r sha256sum | awk '{ hash=$1; sub(/^[^ ]+  \.\//, ""); print $0 "\t" hash }')
}

mapfile -t only_old < <(LC_ALL=C comm -23 <(list_files "$old") <(list_files "$new"))
mapfile -t only_new < <(LC_ALL=C comm -13 <(list_files "$old") <(list_files "$new"))
mapfile -t changed  < <(LC_ALL=C join -t $'\t' <(checksums "$old") <(checksums "$new") |
                        awk -F'\t' '$2 != $3 { print $1 }')

report() {            # report TITLE ITEM...
    local title=$1; shift
    printf '%s (%d)\n' "$title" "$#"
    if (( $# > 0 )); then
        printf '  %s\n' "$@"
    fi
}
report "Only in $old" "${only_old[@]}"
report "Only in $new" "${only_new[@]}"
report "Changed" "${changed[@]}"

(( ${#only_old[@]} + ${#only_new[@]} + ${#changed[@]} == 0 ))

How It Works

  • Argument checks reject a wrong number of arguments or a missing folder with status 2, the usual "usage error" code (lesson 128).
  • list_files runs in a subshell ( ... ) so that cd does not affect the script (lesson 150). It prints paths relative to the folder, such as css/site.css, so the two lists can be compared.
  • LC_ALL=C makes sort, comm and join use plain byte order. comm and join require input sorted in the same order they expect, and setting the same locale for all of them guarantees that.
  • comm -23 <(...) <(...) prints lines only in the first list (columns 2 and 3 hidden); comm -13 prints lines only in the second. Each <(list_files ...) is a separate background process.
  • checksums computes a SHA-256 fingerprint for every file. find -print0, sort -z and xargs -0 keep file names with spaces intact (lesson 112). awk reshapes each line from HASH ./path to path<TAB>HASH.
  • join -t $'\t' matches lines from the two checksum lists that have the same path (the first field) and prints path<TAB>old_hash<TAB>new_hash. Files present in only one folder are left out, which is exactly right, because they are already reported. awk keeps only the paths whose hashes differ.
  • mapfile -t ... < <(...) stores each result in an array in the current shell. With a pipe, the arrays would be filled in a subshell and be empty afterwards.
  • The last line is an arithmetic test whose result becomes the script's exit status: 0 when the folders are identical, 1 when there is any difference, like diff.

Running the Complete Example

Two versions of a small site, v1 and v2, are prepared. index.html was edited, about us.html (a name with a space) was removed and img/logo.png was added. css/site.css and contact.html are the same in both.

./compare-dirs.sh v1 v2; echo "status $?"
Only in v1 (1)
  about us.html
Only in v2 (1)
  img/logo.png
Changed (1)
  index.html
status 1

Comparing a folder with itself and calling the script incorrectly:

./compare-dirs.sh v1 v1; echo "status $?"
./compare-dirs.sh v1; echo "status $?"
./compare-dirs.sh v1 nope; echo "status $?"
Only in v1 (0)
Only in v1 (0)
Changed (0)
status 0
usage: compare-dirs.sh OLD_DIR NEW_DIR
status 2
compare-dirs.sh: not a folder: nope
status 2

The identical comparison reports zero differences and exits with 0, so the script can be used in an if statement or a deployment check: if ./compare-dirs.sh build/ live/ > /dev/null; then echo "nothing to deploy"; fi.

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 Process Substitution with <(...) and >(...) and get answers drawn from it.

Signed-in readers only.