Two-Way Communication With Coprocesses

Keep a program running and exchange data with it over pipes.

macOSbashautomationshellscriptingLow risk
Use coproc NAME { cmd; } to get read and write file descriptors for the process.

01Command

Command
$ coproc BC { bc; }; echo "2+2" >&"${BC[1]}"; read -r answer <&"${BC[0]}"; echo "$answer"

02What it does

A coprocess runs a command in the background with a pipe in each direction, so a script can send input and read output from a stateful program like bc or a database CLI without restarting it. This interactive automation is only possible from a shell.

03Risk

RiskLow risk
RequirementsmacOS default zsh/bash (bash 3.2+; some features need bash 4+ via Homebrew)
CompatibilitymacOS with bash 3.2+ (GNU bash 4+ via Homebrew for advanced features)
!Warning: The file descriptor numbers live in the COPID array and can be clobbered by other redirections; capture them immediately.

04Undo

✓No undo needed — this command does not change persistent state.

05Sources

Last verified: 2026-10-13 · Category: Developer