Process Substitution with <(...) and >(...)
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)runscommandand is replaced by a file name. Reading that file gives you the command's output.>(command)runscommandand 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.
| Tool | Data travels as | How many streams | Needs cleanup |
|---|---|---|---|
Pipe a | b | standard input of b | one | no |
Temporary file (mktemp) | a real file on disk | as many as you create | yes (lesson 124) |
| Process substitution | a file name pointing to a pipe | as many as you write | no |
How It Works
When Bash sees <(command), it does three things before running the outer command:
- It creates a pipe.
- It starts
commandin the background with its standard output connected to the write end of that pipe. - 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
sortprocesses and replaced each<(sort ...)with a/dev/fd/...path. diffopened both paths and read the sorted lines.- For
a.txtandc.txt, the sorted lines match, sodiffprinted nothing and exited with status 0, which triggered&& echo same. - For
a.txtandb.txt,diffreported thataliceappears only in the first list (1d0, "delete line 1") anddaveonly in the second (3a3, "add after line 3"). It exited with status 1, which is howdiffsignals "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_filesruns in a subshell( ... )so thatcddoes not affect the script (lesson 150). It prints paths relative to the folder, such ascss/site.css, so the two lists can be compared.LC_ALL=Cmakessort,commandjoinuse plain byte order.commandjoinrequire 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 -13prints lines only in the second. Each<(list_files ...)is a separate background process.checksumscomputes a SHA-256 fingerprint for every file.find -print0,sort -zandxargs -0keep file names with spaces intact (lesson 112).awkreshapes each line fromHASH ./pathtopath<TAB>HASH.join -t $'\t'matches lines from the two checksum lists that have the same path (the first field) and printspath<TAB>old_hash<TAB>new_hash. Files present in only one folder are left out, which is exactly right, because they are already reported.awkkeeps 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.