How to Use Process Substitution in Bash: Simple Guide
In Bash,
process substitution lets you use the output of a command as if it were a file by using the syntax <(command) or >(command). This helps when commands expect file inputs but you want to use dynamic command outputs instead.Syntax
Process substitution uses these forms:
<(command): Runscommandand provides its output as a file-like input.>(command): Sends input tocommandas if writing to a file.
This creates a temporary named pipe or file descriptor that commands can read from or write to.
bash
diff <(ls dir1) <(ls dir2)
Example
This example compares the contents of two directories using diff with process substitution. It runs ls on each directory and passes the outputs as files to diff.
bash
mkdir -p dir1 dir2 echo "apple" > dir1/file1.txt echo "banana" > dir1/file2.txt echo "apple" > dir2/file1.txt echo "orange" > dir2/file2.txt diff <(ls dir1) <(ls dir2)
Output
2c2
< banana
---
> orange
Common Pitfalls
Common mistakes include:
- Trying to use process substitution in shells that don't support it (like plain sh).
- Confusing process substitution with command substitution (
$(command)), which captures output as a string, not a file. - Using process substitution with commands that require seekable files, since pipes are not seekable.
Example of wrong usage and fix:
bash
# Wrong: trying to read from a command output directly without process substitution
cat $(ls dir1)
# Right: use process substitution to compare directory listings
diff <(ls dir1) <(ls dir2)Quick Reference
Tips for using process substitution:
- Use
<(command)when a command needs a file input but you want to provide dynamic output. - Use
>(command)to send output to a command that reads from a file. - Works only in Bash and some other advanced shells, not in plain sh.
- Useful for commands like
diff,cmp, or any tool expecting filenames.
Key Takeaways
Process substitution lets you treat command output as a file input using
<(command).It is useful when commands require file arguments but you want to use dynamic data.
Process substitution creates temporary pipes or file descriptors behind the scenes.
It only works in Bash and compatible shells, not in plain sh.
Avoid using it with commands that need seekable files, as pipes are not seekable.