Forrest logo
back to the coproc tool

coproc:tldr:d3ee2

coproc: Create and use a coprocess running `bc`.
$ coproc BC { bc --mathlib; }; echo "1/3" >&"${BC[1]}"; read output <&"${BC[0]}"; echo "$output"
try on your machine

This command sets up a coprocess, which is a form of process substitution in the shell. A coprocess allows you to communicate with a command as if it were a file.

Here is a breakdown of the command:

  1. coproc BC { bc --mathlib; }:

    • coproc is the keyword used to establish a coprocess.
    • BC is the name of the coprocess, which is used as an array variable to refer to the input/output file descriptors of the coprocess.
    • { bc --mathlib; } is the command that the coprocess runs. In this case, it launches the bc command with the --mathlib option, which loads the math library for advanced mathematical calculations.
  2. echo "1/3" >&"${BC[1]}":

    • echo "1/3" outputs the string "1/3".
    • >&"${BC[1]}" redirects the output of the echo command to the coprocess's input file descriptor. ${BC[1]} is the second element (index 1) of the BC coprocess array, which refers to the output file descriptor of the coprocess.
  3. read output <&"${BC[0]}":

    • read output reads input from the coprocess's output file descriptor and stores it in the variable output.
    • <&"${BC[0]}" redirects the coprocess's output file descriptor to the input of the read command. ${BC[0]} is the first element (index 0) of the BC coprocess array, which refers to the input file descriptor of the coprocess.
  4. echo "$output":

    • echo "$output" outputs the value stored in the output variable, which is the result of the previous calculation performed by the coprocess.

To summarize, the command establishes a coprocess running the bc command with the math library enabled. It then sends the string "1/3" to the coprocess for calculation, reads the output from the coprocess, and finally, prints the result. In this case, the result should be "0.33333333333333333333" (the decimal representation of 1/3 according to bc's math library).

This explanation was created by an AI. In most cases those are correct. But please always be careful and never run a command you are not sure if it is safe.
back to the coproc tool