← Back to Bash Course | Chapter 11: Process Management | Lesson 10 of 12

Command Substitution vs Process Substitution

Command substitution captures a command's output as text you can store or reuse, while process substitution lets a command's output be treated like a temporary file.

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

bash
#!/bin/bash
today_year=$(date +%Y)
echo "the year variable holds: $today_year"

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

bash
#!/bin/bash
cat <(echo "generated on the fly")

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

bash
#!/bin/bash
diff <(printf "a\nb\nc\n") <(printf "a\nx\nc\n") || echo "differences were found above"

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

bash
#!/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")
Common Mistakes
  1. Confusing $(...) (command substitution, produces text) with <(...) (process substitution, produces a file-like path).
  2. Trying to use process substitution in a POSIX sh script; <(...) is a bash-specific (and a few other shells') feature, not portable to plain sh.
  3. Forgetting command substitution strips trailing newlines from the captured output, which can matter when the output's exact formatting is significant.
Chapter Summary
  • $(command) runs command and substitutes its stdout as a string, with trailing newlines stripped.
  • <(command) runs command and 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 diff without creating temp files manually.
  • Both features run their command in a subshell, so variables set inside them are not visible afterward.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.