coproc

Start a background co-process and communicate with it via pipes in Bash.

Category: Shell bash process-control pipes advanced

Install

# coproc is a Bash keyword (not a separate binary).
# Available in Bash 4+.

bash --version

What it does

coproc launches a command as a co-process running in the background, with a two-way pipe attached. You can send input to the process and read output from it asynchronously.

How it works (mechanical)

  • Creates a background subshell running the given command.
  • Establishes two file descriptors: one for writing, one for reading.
  • Stores them in an array variable (default name: COPROC).
  • Enables bidirectional communication via redirection operators.
  • Process runs concurrently with main shell.

Quick Start

# Start a simple coprocess
coproc myproc { bc -l; }

# Send data
echo "2+2" >&"${myproc[1]}"

# Read result
read result >&"${myproc[0]}"
echo "$result"

10 Practical Examples

# 1) Basic coprocess
coproc CALC { bc; }
# 2) Send calculation
echo "5*5" >&"${CALC[1]}"
# 3) Read output
read output >&"${CALC[0]}"
echo "$output"
# 4) Use without naming (default COPROC array)
coproc bc
echo "3+7" >&"${COPROC[1]}"
read result >&"${COPROC[0]}"
# 5) Close write descriptor
exec {CALC[1]}>&-
# 6) Use coproc in script automation
coproc ping localhost
# 7) Capture asynchronous output
read line >&"${COPROC[0]}"
# 8) Check coprocess PID
echo $CALC_PID
# 9) Wait for coprocess
wait $CALC_PID
# 10) Kill coprocess
kill $CALC_PID

Notes & Gotchas

  • Requires Bash 4 or newer.
  • Advanced feature — not POSIX shell compatible.
  • File descriptor handling can be tricky.
  • Useful for persistent background helpers.
  • Be sure to close descriptors when done.

Historical Context

Bash introduced coproc to simplify asynchronous process communication without manual pipe setup. It provides structured concurrency within shell scripts.

Modern Equivalent

More complex concurrent scripting often uses tools like tmux, named pipes, or external languages (Python, Go). However, coproc remains powerful for advanced Bash automation.

Related Commands

  • disown — manage background jobs.
  • jobs — list shell jobs.
  • wait — wait for process termination.
  • kill — send signals to processes.
  • exec — manipulate file descriptors.