Process Substitution in Practice (diff <(...) <(...))
In this page:
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
#!/bin/bash
diff <(printf "a\nb\nc\n") <(printf "a\nb\nc\n") && echo "identical output, no differences"
Login to try C/C++/Java/PHP code in the editor
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
#!/bin/bash
if diff <(printf "a\nb\n") <(printf "a\nc\n") > /dev/null; then
echo "no differences"
else
echo "differences were found"
fi
Login to try C/C++/Java/PHP code in the editor
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
#!/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
Login to try C/C++/Java/PHP code in the editor
- 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.
- Forgetting
diffreturns a non-zero exit status when differences are found, which is expected behavior, not an error. - Using process substitution in a POSIX
shscript and being confused why it fails; it's a bash (and a few other shells') extension.
diff <(cmd1) <(cmd2)compares two commands' live output without intermediate temp files.diffexits 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.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first:
- getopts for Parsing Command-Line Flags
- Positional Parameters and shift
- Process Substitution in Practice (diff <(...) <(...))
- Arrays of Arguments ("$@" vs "$*" Quoting Difference)
- Nameref Variables (declare -n) for Passing Arrays by Reference
- Heredoc Templating (Generating a Config File from Variables)
- Default/Fallback Argument Handling