The Analogy: A Water Utility's Temporary Standpipe and Meter Cabin
A construction crew arrives on a street with no permanent water connection, but they need a metered supply for the week. The water utility does not dig a new main; instead an engineer fits a temporary standpipe onto the nearest fire hydrant. A standpipe is a portable column with its own meter and a perfectly ordinary threaded outlet on the side. The crew screws their hose onto that outlet exactly as they would onto a garden tap in a back yard, and the hose has no idea it is drinking from a hydrant rather than from a wall fitting. This is precisely what process substitution does with <(command): the shell fits a temporary, file-shaped outlet onto the live output of a running command, so any program that expects a filename can connect to it and read the stream without ever knowing there is no real file behind it.
Sometimes the flow runs the other way. The crew has murky water to get rid of, and the utility fits a second temporary connector -- a drain coupling that carries whatever the crew pours in away to a tanker for treatment. The crew pours into a standard-looking inlet; the water disappears into a process they never see. That reverse fitting is >(command): a file-shaped handle you write to, where everything you send is quietly piped into another command's standard input. A splitter that sends the same flow both into a holding bucket and into the treatment drain is the everyday tee >(...) pattern.
For work that must not disturb the live mains, the utility wheels in a self-contained meter cabin. Inside it the engineers open their own valves, run their own gauges, and jot figures on their own clipboard. When the tests are done they wheel the cabin away, and nothing they did inside is bolted to the street: the main's pressure, its valve positions, the readings on the public meter are all exactly as before. A subshell -- the parenthesised ( ... ) -- is that cabin. Commands inside it run in a child process with their own copy of the environment, so a cd, a changed variable, or a set option lives and dies inside the parentheses and never reaches the parent shell.
The failure mode is what the crew forgets at the end of the week. The standpipe was metered live, and none of the water was ever stored: once the tanker has driven off there is no barrel left to re-measure, so a reading not taken while it flowed is gone for good. A process-substitution handle is the same one-way live stream -- you cannot rewind it, seek back through it, or read it twice, and the writing side may still be draining after your main command has already returned. Worse, the meter cabin's isolation cuts both ways: a crew that carefully totals the week's usage on the clipboard inside the cabin, then wheels the cabin away, has thrown the total out with it. That is the classic trap where a counter incremented inside a piped while loop -- which Bash runs in a subshell -- reads back as zero the moment the pipe ends.
Syntax or Core Structure
Process substitution has two shapes. Reading form <(command) runs the command and hands you a filename that, when opened, delivers the command's standard output. Writing form >(command) hands you a filename that feeds anything written to it into the command's standard input. Bash implements both with an anonymous pipe exposed under a path like /dev/fd/63, so the program on the other end thinks it opened an ordinary file. The most useful everyday shape is feeding a while read loop from <(...) using an input redirect, written done < <(...) -- note the mandatory space between the redirect < and the substitution <(.
#!/usr/bin/env bash
set -uo pipefail
# Read a command's output as if it were a file on disk.
while read -r line; do
echo "got: $line"
done < <(printf '%s\n' alpha beta gamma)
Output:
got: alpha
got: beta
got: gamma
The loop runs in the current shell, not in a subshell, because its input arrives through a redirect rather than through a pipe. That distinction is the whole point: had we written printf ... | while read ..., the loop would run in a child process and any variable it set would vanish when the pipe closed. Because <(...) presents the stream as a file the loop reads from, the shell keeps the loop in the foreground, so counters, arrays, and flags updated inside it survive after done. The stream itself is live and one-directional: you read it once, front to back, and there is no seeking back to the start.
Technical Depth: Streams That Pretend To Be Files
Process substitution earns its keep whenever a program insists on a filename but the data you have is the output of another command. Rather than writing that output to a temporary file, cleaning it up afterwards, and hoping two runs do not collide, you hand the program a substitution and let the kernel wire the pipe.
Comparing two streams with diff
The tool diff compares two files. To compare two commands -- say, two directory listings, or the same data sorted two ways -- wrap each in <(...):
#!/usr/bin/env bash
set -uo pipefail
diff <(printf '%s\n' apple banana cherry) <(printf '%s\n' apple blueberry cherry) || true
echo "compared"
Output:
2c2
< banana
---
> blueberry
compared
Each <(...) becomes a filename that diff opens and reads; neither list ever touches disk. The || true is deliberate: diff exits non-zero when the files differ, which under set -e would abort the script before the final echo, so we neutralise that expected non-zero status. The 2c2 line is diff reporting that line 2 changed, with the two versions shown around the --- marker.
Which construct does what
The four related constructs are easy to confuse. This table fixes the differences in one place.
| Construct | Purpose | Runs in a child process? |
|---|---|---|
<(command) | read a command's output as if it were a file | yes for the command; the reader stays in the current shell |
>(command) | write to a command as if it were a file | yes, and asynchronously |
( commands ) | isolate cd, variable, and set changes | yes -- every change is discarded on exit |
$(command) | capture a command's output into a string | yes; the capture itself runs in a subshell |
Writing to a process with the output form
The >(...) form is the mirror image: it is a filename you write to, and the bytes flow into a command's standard input. Combined with tee, it lets one stream fan out to several consumers at once.
#!/usr/bin/env bash
set -uo pipefail
# Split one stream: keep the raw order in one file, a sorted copy in another.
printf '%s\n' gamma alpha beta | tee >(sort -o sorted.txt) > raw.txt
wait
echo "raw order:"
cat raw.txt
echo "sorted copy:"
cat sorted.txt
Output:
raw order:
gamma
alpha
beta
sorted copy:
alpha
beta
gamma
tee sees two destinations: the process substitution (which forwards into sort) and its own standard output (redirected into raw.txt). The crucial detail is wait. The sort inside >(...) runs asynchronously, on its own schedule, so without wait the script could reach cat sorted.txt before sort had finished writing, and print an empty or partial file. Because the writing side is a detached process, you must synchronise on it explicitly; there is no automatic back-pressure telling the parent it is safe to read.
Subshells keep their changes to themselves
Parentheses run their contents in a subshell -- a child with a private copy of the environment. Anything it changes is discarded when the closing parenthesis is reached.
#!/usr/bin/env bash
set -uo pipefail
x=1
( x=2; echo "inside subshell: $x" )
echo "outside subshell: $x"
Output:
inside subshell: 2
outside subshell: 1
Inside the parentheses x really does become 2, and any cd or export would also take effect -- but only within that child. When the subshell exits, the parent's x is still 1. This isolation is a feature when you want to cd somewhere, do work, and return without disturbing the caller's directory. It becomes a trap the moment you expect a value computed inside a subshell to be visible outside it.
The counter that reads back as zero
Put the two ideas together and you see the most notorious Bash bug of all. A while loop on the receiving end of a pipe runs in a subshell, so a counter it increments is lost. Feeding the same loop from <(...) keeps it in the current shell, and the counter survives.
#!/usr/bin/env bash
set -uo pipefail
count=0
printf '%s\n' a b c | while read -r _; do
count=$((count + 1))
done
echo "after pipe: $count"
count=0
while read -r _; do
count=$((count + 1))
done < <(printf '%s\n' a b c)
echo "after redirect: $count"
Output:
after pipe: 0
after redirect: 3
The first loop genuinely counts to three, but it does so inside the pipe's subshell -- the meter cabin -- and when the pipe closes the cabin is wheeled away with the total still on its clipboard, so the parent reads count as its original 0. The second loop is identical except that its input arrives through < <(...), which keeps the loop in the foreground shell, so count is 3 afterwards. Whenever a loop must accumulate a total, an array, or a flag, feed it with process substitution, never with a pipe.
Real World Example: Reconciling Two Inventory Snapshots
A warehouse produces two stock snapshots a day, and the operations team wants a quick report of which items changed quantity between the morning and evening counts. The two snapshots are plain sku quantity lines, and -- as real exports always are -- they are in different orders. The script below compares them without writing a single temporary file, using <(...) both to drive the outer loop and to look each item up in the evening data, and it keeps a running count of changes in a variable that must survive the loop.
#!/usr/bin/env bash
set -uo pipefail
morning='widget 40
gadget 12
sprocket 7
cog 100'
evening='cog 100
widget 38
gadget 12
sprocket 7'
changed=0
while read -r sku qty_m; do
qty_e=$(grep -m1 "^$sku " <(printf '%s\n' "$evening") | awk '{ print $2 }')
if [[ "$qty_m" != "$qty_e" ]]; then
printf 'CHANGED %-10s %s -> %s\n' "$sku" "$qty_m" "$qty_e"
changed=$((changed + 1))
fi
done < <(printf '%s\n' "$morning")
printf 'total changed: %s\n' "$changed"
Output:
CHANGED widget 40 -> 38
total changed: 1
The outer while loop is fed by done < <(printf '%s\n' "$morning"), so it runs in the current shell and its changed counter is real, not a subshell casualty. For each morning line it splits sku and qty_m with read, then looks up the same SKU in the evening snapshot with grep -m1 "^$sku " <(printf '%s\n' "$evening"), pulling the quantity field out with awk. The evening data never becomes a file; the substitution presents it as one for the length of that single grep. When the two quantities differ, the script prints an aligned line and bumps the counter.
Reading the report is straightforward: only widget moved, from 40 down to 38, so one line is printed and the footer confirms total changed: 1. The gadget, sprocket, and cog lines all matched their evening counterparts and produced no output. The %-10s field keeps the SKU column aligned regardless of name length, and because both snapshots are read in the fixed order the loop imposes, the output is identical on every run.
The script's honesty lies in what it cannot see. Its comparison is strictly one-directional: it walks the morning list and asks whether each item changed, so an item that appears only in the evening snapshot -- a product added during the day -- is never examined and never reported, and the total can read 0 even though stock genuinely changed. A SKU present in the morning but missing from the evening lookup yields an empty qty_e, which prints as NAME old -> with a blank right-hand side rather than a clear "removed" message. The lookup grep -m1 "^$sku " also treats the SKU as a regular expression, so a SKU containing a . or * could match the wrong row, and running a fresh grep inside the loop makes the whole reconciliation quadratic -- fine for a few dozen items, wasteful for tens of thousands, where a single join on two sorted streams would be the right tool.
Common Mistakes
- Piping into a
whileloop and expecting a counter to survive.cmd | while read ...; do n=$((n+1)); doneruns the loop in a subshell, sonis zero afterwards. Feed the loop withdone < <(cmd)instead. - Omitting the space in
< <(...). Writingdone <<(cmd)makes Bash see the<<of a here-document and fail with a syntax error. The redirect<and the substitution<(are two separate tokens and need a space between them. - Trying to read a process substitution twice. The handle is a live, one-way pipe, not a file on disk. You cannot rewind it or open it a second time; if two consumers need the data, capture it into a variable or a real temporary file first.
- Reading a
>(...)target before its process has finished. The command inside>(...)runs asynchronously, so a file it writes may be incomplete until youwait. Skipping thewaitgives intermittent empty or truncated results. - Assuming
>(...)output interleaves predictably with normal output. Because the substituted process runs on its own schedule, its writes to a shared terminal can arrive before, after, or between the main stream's lines. Direct it to its own file when order matters. - Expecting
cdor variable changes inside( ... )to persist. The parentheses create a subshell; a directory change or assignment inside them vanishes on exit. Use braces{ ...; }to group commands without a subshell. - Feeding a substitution to a program that needs a seekable file. Some tools memory-map or re-open their input, and a
/dev/fd/NNpipe cannot be seeked. Such a program will error out or read nothing; give it a genuine file instead. - Using process substitution under
#!/bin/sh. It is a Bash extension, not POSIX. A script with ashshebang, or one run withsh script, will reject<(...)outright. - Believing
var=$(cmd)letscmdchange the outer shell. Command substitution also runs in a subshell, so a variable assigned or a shell option set inside it does not leak back to the caller.
Best Practices
- Feed accumulating loops with
< <(...), never a pipe. Any loop that must leave a counter, array, or flag behind belongs in the current shell. The process-substitution redirect keeps it there; a pipe exiles it to a subshell. - Use
( ... )on purpose, and{ ...; }when you do not want a subshell. Parentheses are the right tool for "cd here, do work, come back untouched". Curly braces group commands in the current shell when you need their side effects to persist. - Prefer process substitution over temporary files for transient data. It removes the whole ritual of naming a temp file, trapping to clean it up, and guarding against two runs colliding on the same path.
- Always
waitafter writing through>(...)before reading the result. The substituted process is asynchronous, so synchronise on it explicitly rather than hoping it finished in time. - Keep the Bash shebang when you use substitutions.
<(...)and>(...)are Bash extensions; write#!/usr/bin/env bashand do not run the script withsh. - Reach for
diff <(...) <(...)orcommto compare command outputs. Comparing two live streams directly is clearer and cheaper than dumping both to files first. - Capture a stream once if it must be read more than once. A substitution is single-use; store its output in a variable or a real file when two consumers need it.
- Use
joinorcommon sorted streams for large reconciliations. Runninggrepinside a loop is quadratic; a single pass over two sorted inputs scales far better.
Practice Exercises
- Make the counter survive. Take a
cmd | while read ...; do n=$((n+1)); donethat printsnas zero, and rewrite it withdone < <(cmd)so the total is correct. Print the result from both forms to prove the difference. - Compare without temp files. Write two commands whose outputs differ by exactly one line, compare them with
diff <(...) <(...), and explain each part of thediffreport. Neither output may touch disk. - Fan out with tee. Send one stream simultaneously to a file and to
wc -lusingtee >(...), then usewaitand read both results so the output is identical on every run. - Reconcile in both directions. Extend the inventory example so an item present only in the evening snapshot is reported as
ADDED, and a morning item missing from the evening is reported asREMOVEDinstead of printing a blank quantity. Show the output for one added item and one removed item.