Process Substitution in Bash

Process substitution is a feature in Bash that allows you to use the input or output of a command as if it were a file or a stream. It provides a convenient way to pass the output of a command as input to another command or to a function. Process substitution is denoted by the use of <() for command substitution and >() for output substitution.

Here's a detailed explanation with examples:

Input Process Substitution (<())

Captures the output of a command and feeds it as input to the subsequent command.

Compare two files using diff

diff <(cat file1.txt) <(cat file2.txt)

In this example, the contents of file1.txt and file2.txt are passed as input to the diff command using process substitution. The <() syntax creates temporary files or named pipes to hold the output of the enclosed commands, and these are then used as arguments to diff.

Read from a process

while read line; do echo "Line: $line" done < <(echo -e "one\ntwo\nthree")

Here, the echo command generates three lines, and the read command reads from the process substitution as if it were a file.

Output Process Substitution (>())

Redirects the output of a command into a temporary file used by the following command.

Redirect output to a command

echo "Hello, World!" > >(grep World)

In this example, the output of the echo command is redirected to the grep command using process substitution. The >() syntax creates a temporary file or named pipe to capture the output, and grep then reads from this.

Save output to a file and display on the terminal

command > >(tee output.txt)

Here, the output of the command is saved to a file (output.txt) and simultaneously displayed on the terminal using tee.

Combining Input and Output Process Substitution

Concatenate and grep

cat <(cat file1.txt) <(cat file2.txt) > >(grep keyword)

This example combines input and output process substitution. The contents of file1.txt and file2.txt are concatenated and then passed as input to grep. The result is also displayed on the terminal.

Nested Process Substitution

Sort the result of a command

sort <(command1 <(command2))

Here, the output of command2 is passed as input to command1, and the combined output is then sorted using process substitution.


Process substitution is a powerful feature that enhances the flexibility of Bash scripting by treating command output as if it were a file or stream. Keep in mind that process substitution is specific to Bash and may not be available in other shell environments.