Problem Statement
Explain process substitution in bash. How does it differ from command substitution and when should you use it?
Explanation
Process substitution treats command output as file using <(command) for reading or >(command) for writing. Bash creates temporary FIFO (named pipe) or /dev/fd/ file descriptor connected to command output/input. Syntax: <(command) creates readable file, >(command) creates writable file. Use when commands expect files but you have command output.
Examples:
```bash
# Compare outputs of two commands
diff <(ls dir1) <(ls dir2)
# Sort and compare without temp files
comm <(sort file1) <(sort file2)
# Feed command output to multiple commands
tee >(process1) >(process2) < input
# Read from multiple sources
while read line; do echo "$line"; done < <(cat file1 file2)
```
Difference from command substitution $(): command substitution captures output as string for variable assignment or inline use: VAR=$(command) or echo "Result: $(command)". Process substitution creates file-like interface for commands expecting file arguments. Command substitution stores all output in memory, process substitution streams data through pipe.
Use cases: commands requiring file arguments (diff, comm, paste, join), avoiding temporary files, parallel processing (multiple outputs with tee), reading output preserving while loop variables (avoiding subshell issue). Example:
```bash
# This works (process substitution avoids subshell)
while read line; do
COUNT=$((COUNT+1))
done < <(cat file)
echo "Lines: $COUNT" # COUNT visible
# This doesn't (pipe creates subshell)
cat file | while read line; do
COUNT=$((COUNT+1))
done
echo "Lines: $COUNT" # COUNT not visible
```
Limitations: not POSIX portable (bash, zsh, ksh only), may not work with commands checking file type, order of execution may differ from expectation. Understanding process substitution enables advanced I/O manipulation without temporary files, cleaner code, and solves subshell variable visibility issues.
Practice Sets
This question appears in the following practice sets: