Process substitution

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-05-01

I wanted to use the diff command to compare a function repeated almost verbatim within a file. I found a way to focus on that repeated function with sed:

First instance: $ sed -n -e '286,541p' resources/js/maps.js

Second: $ sed -n -e '16,266p' resources/js/maps.js

When I tried to diff I ran into a problem: diff could only compare files - whereas I was dealing with process outputs. The solution was process substitution:

diff <(sed -n -e '286,541p' resources/js/maps.js) <(sed -n -e '16,266p' resources/js/maps.js) | nvim
echo >(true)
# >(true) turned into fd 12
/dev/fd/12

The name of this file is passed as an argument to the current command as the result of the expansion

Process substitution can compare the output of two different commands, or even the output of different options to the same command:

comm <(ls -l) <(ls -al)
...
total 12
...
total 20

Or it can compare the contents of two directories:

diff <(ls $first_directory) <(ls $second_directory)

Resources