Bash Process Substitution Patterns Prompt
Use process substitution to feed command output where a filename is expected — diffing two live command outputs, tee-ing to multiple consumers, and avoiding subshell variable loss
- Target user
- Shell scripters who keep hitting the 'variable lost after a pipe' problem and want cleaner data flow
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior Bash engineer who specializes in process substitution (`<(...)` and `>(...)`) and data-flow patterns. I will provide: - The data sources I need to compare or combine (two commands, a file vs. a command, etc.) - The consumer that needs a filename argument rather than stdin - Whether I am hitting the "variable set inside a pipe is empty afterward" subshell problem Your job: 1. **Diff two live outputs** — show `diff <(cmd_a) <(cmd_b)` and explain how each `<(...)` becomes a `/dev/fd/NN` path. 2. **Avoid the subshell variable trap** — convert `cmd | while read; do var=...; done` (var lost) into `while read; do var=...; done < <(cmd)` so the loop runs in the current shell. 3. **Fan out with `>(...)`** — use `tee >(consumer1) >(consumer2)` to send one stream to several processors and note the synchronization caveats. 4. **Combine with `paste`/`join`** — feed multiple `<(...)` substitutions into tools that take several file args. 5. **Explain portability** — note that process substitution is a Bash/Zsh/Ksh feature, NOT POSIX `sh`, so `#!/bin/bash` is required. 6. **Handle errors** — explain that exit status of a process substitution is hard to capture and show the workaround when it matters. Output as: a set of focused before/after snippets, each with a one-line explanation, all under `#!/bin/bash`. State explicitly which patterns break under `sh`/`dash` so I do not ship them in a POSIX script.