Bash Coprocess Bidirectional Pipe Orchestration Prompt
Drive a long-running interactive child process from a Bash script using a coproc so you can stream commands in and read responses out without re-spawning the process per call
- Target user
- Platform engineers wiring shell automation around stateful CLIs (database REPLs, gpg-agent, custom daemons)
- Difficulty
- Advanced
- Tools
- Claude, ChatGPT
The prompt
You are a senior automation engineer who specializes in Bash inter-process communication and the `coproc` keyword.
I will provide:
- The interactive command I need to keep alive (e.g. `psql`, `bc`, a custom REPL) and its prompt/output delimiter behavior
- The sequence of requests I want to send and how I expect to recognize each reply boundary
- My Bash version and target platform (so you can flag `coproc` portability limits)
Your job:
1. **Spawn the coprocess** — scaffold `coproc NAME { cmd; }` and explain the auto-created `NAME[0]` (read) and `NAME[1]` (write) file descriptors plus `NAME_PID`.
2. **Write requests safely** — show how to `printf '%s\n' "$req" >&"${NAME[1]}"` and why unbuffered/line-buffered output on the child matters.
3. **Read replies without hanging** — implement a bounded `read -r -u "${NAME[0]}"` loop with `read -t` timeouts and a sentinel/delimiter to detect end-of-reply.
4. **Guard against deadlock** — explain the classic pipe-buffer deadlock and how to avoid it (one coproc per shell limitation, fd leakage into subshells).
5. **Tear down cleanly** — close both fds with `exec {fd}>&-`, signal the child, and `wait "$NAME_PID"`, capturing its exit status.
6. **Handle the single-coproc constraint** — if I need more than one, show the manual `mkfifo` + background-process alternative.
Output as: one annotated `.sh` script using `set -euo pipefail`, with a clearly marked request/response loop and inline comments at each fd operation.
Call out explicitly any place where a missing line-buffer flush on the child will silently hang the read loop forever.