Command Substitution vs Process Substitution
In this page:
Command Substitution Basics
$(command) executes command and replaces itself with that command's stdout, captured as a string with any trailing newline removed, which can then be assigned to a variable.
Example: Command Substitution Basics
#!/bin/bash
today_year=$(date +%Y)
echo "the year variable holds: $today_year"
Login to try C/C++/Java/PHP code in the editor
Process Substitution Basics
<(command) runs command and exposes its output through a special path (typically /dev/fd/N) that other commands can read from as though it were a real file, without ever writing to disk.
Example: Process Substitution Basics
#!/bin/bash
cat <(echo "generated on the fly")
Login to try C/C++/Java/PHP code in the editor
Comparing Two Commands' Output
A classic use of process substitution is feeding two commands' output directly into diff as if they were files, avoiding the need to manually create and clean up temporary files.
Example: Comparing Two Commands' Output
#!/bin/bash
diff <(printf "a\nb\nc\n") <(printf "a\nx\nc\n") || echo "differences were found above"
Login to try C/C++/Java/PHP code in the editor
Choosing the Right Tool
Use command substitution when you need the output as a plain string (to store in a variable or build another string); use process substitution when a command expects a filename argument but you want to hand it another command's live output instead.
Example: Choosing the Right Tool
#!/bin/bash
line_count=$(printf "a\nb\nc\n" | wc -l)
echo "captured as text: $line_count lines"
while read -r line; do
echo "from process substitution: $line"
done < <(printf "x\ny\n")
Login to try C/C++/Java/PHP code in the editor
- Confusing
$(...)(command substitution, produces text) with<(...)(process substitution, produces a file-like path). - Trying to use process substitution in a POSIX
shscript;<(...)is a bash-specific (and a few other shells') feature, not portable to plainsh. - Forgetting command substitution strips trailing newlines from the captured output, which can matter when the output's exact formatting is significant.
$(command)runscommandand substitutes its stdout as a string, with trailing newlines stripped.<(command)runscommandand exposes its output as a path to a readable file-like object, often/dev/fd/N.- Process substitution is commonly used to compare the output of two commands with
diffwithout creating temp files manually. - Both features run their command in a subshell, so variables set inside them are not visible afterward.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: