← Back to Bash Course | Chapter 13: Advanced Scripting | Lesson 3 of 7

Process Substitution in Practice (diff <(...) <(...))

You can compare the results of two different commands directly, as if they were two files, without ever saving them to disk first.

Comparing Two Command Outputs

diff <(cmd1) <(cmd2) lets you diff the live output of two commands directly, which is much more convenient than manually redirecting each to a temp file, diffing those, and cleaning up afterward.

Example: Comparing Two Command Outputs

bash
#!/bin/bash
diff <(printf "a\nb\nc\n") <(printf "a\nb\nc\n") && echo "identical output, no differences"

Detecting a Difference

diff's exit status doubles as a useful signal: 0 means no differences, 1 means differences were found, which lets a script branch on the comparison result directly.

Example: Detecting a Difference

bash
#!/bin/bash
if diff <(printf "a\nb\n") <(printf "a\nc\n") > /dev/null; then
    echo "no differences"
else
    echo "differences were found"
fi

Comparing Sorted Versions of Data

Process substitution composes well with other pipelines; comparing the sorted output of two data sets is a common real-world use for checking whether two lists contain the same elements regardless of order.

Example: Comparing Sorted Versions of Data

bash
#!/bin/bash
list_a="banana\napple\ncherry"
list_b="cherry\nbanana\napple"
if diff <(printf "$list_a" | sort) <(printf "$list_b" | sort) > /dev/null; then
    echo "both lists contain the same elements"
fi
Common Mistakes
  1. Trying to use process substitution with commands that require a real seekable file rather than a pipe-like descriptor; some tools don't support it.
  2. Forgetting diff returns a non-zero exit status when differences are found, which is expected behavior, not an error.
  3. Using process substitution in a POSIX sh script and being confused why it fails; it's a bash (and a few other shells') extension.
Chapter Summary
  • diff <(cmd1) <(cmd2) compares two commands' live output without intermediate temp files.
  • diff exits 0 if inputs are identical and 1 if they differ, which scripts can check directly.
  • Process substitution can be used anywhere a filename is expected, not just with diff.
  • Each <(...) runs its command in a subshell, so it cannot leak variables back to the calling script.

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.