coproc
Run a command in the background
TLDR
Run a subshell asynchronously
Create a coprocess with a specific name
Write to a specific coprocess stdin
Read from a specific coprocess stdout
Create a coprocess which repeatedly reads stdin and runs some commands on the input
Create a coprocess which repeatedly reads stdin, runs a pipeline on the input, and writes the output to stdout
Create and use a coprocess running bc
SYNOPSIS
coproc [NAME] { COMMAND }
PARAMETERS
NAME
An optional name to assign to the array holding the process information. If omitted, the default name `COPROC` is used.
COMMAND
The command to execute as a coprocess. This can be a simple command, a pipeline, or a more complex shell script.
DESCRIPTION
The `coproc` command in Linux allows you to execute another command in the background as a coprocess.
A coprocess runs concurrently with the current shell process.
Standard input and output streams are connected via pipes between the two processes.
The main shell can then read from and write to the coprocess, enabling two-way communication and parallel execution.
This is especially useful for long-running tasks where the main script needs to interact with the background process or wants to do something else while waiting for the background process to finish. `coproc` command creates an array variable containing the process ID of the coprocess and file descriptors for interacting with it. The name of the array can be specified or defaults to `COPROC`.
The coprocess runs in a subshell environment.
Upon completion, the return code of the last command will be passed to the standard `?` variable.
CAVEATS
The coprocess runs in a subshell, meaning variable assignments within the coprocess will not affect the parent shell's environment. File descriptors need to be explicitly closed after use to prevent resource leaks.
ARRAY VARIABLE STRUCTURE
The variable created (NAME or COPROC) is an array, and contains the process information.
${NAME[0]} contains the process ID of the coprocess.
${NAME[1]} is the file descriptor for writing to the coprocess' standard input.
${NAME[2]} is the file descriptor for reading from the coprocess' standard output.
ERROR HANDLING
Errors inside the coprocess won't automatically halt the main script. Error handling needs to be explicitly implemented in the parent script. The coprocess' exit status is available in the `$?` variable after waiting for the coprocess to complete.
SEE ALSO
&, wait(1), pipe(7)