Bash Process Substitution
Process substitution feeds a command's output to another command as if it were a file. Bash builds a temporary path for the output, and the receiving command reads from that path.
Compare two sorted lists without temp files
Both files are created first, then diff compares their sorted outputs. The sorted lists differ on one name, so diff reports that line.
printf 'ana\nben\ncid\n' > team-a.txt
printf 'ana\nben\ndan\n' > team-b.txt
diff <(sort team-a.txt) <(sort team-b.txt) || echo "teams differ"Feed command output to a command that wants a file
grep reads from the process substitution as if it were a file. Only lines holding the letter a are printed.
grep "a" <(printf 'apple\nbanana\ncherry\n')Send output into a command with >()
echo writes into the process substitution, and tr turns the text uppercase into a file. A short pause lets that background step finish before cat reads the file.
echo "hello log" > >(tr 'a-z' 'A-Z' > lower.txt)
sleep 0.2
cat lower.txtExample
printf 'ana\nben\ncid\n' > team-a.txt
printf 'ana\nben\ndan\n' > team-b.txt
diff <(sort team-a.txt) <(sort team-b.txt) || echo "teams differ"
grep "a" <(sort team-a.txt)Key points
- <(): feeds a command's output into a command that expects a file.
- >( ): sends output into a command that reads it as its input.
- Use <() when a tool takes file names but you only have command output.
- The <() path points to a pipe, not to a file on disk.
- Process substitution avoids a named temporary file for a one-off job.
- diff <(sort a) <(sort b): compares two sorted outputs with no temp files.
In this example, the two printf commands create the two team files first. The diff command then compares their sorted outputs through process substitution. The lists differ on one name, so diff reports that line and the script prints the closing line. The last command feeds the sorted first team to grep, which prints only the line holding the letter a.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does diff <(sort team-a.txt) <(sort team-b.txt) compare?