Coprocesses are a feature of bash which allow you to communicate with the stdin and stdout of a subprocess. I illustrate this by having a bash script to interact with “dc”, the arbitrary precision calculator, to sum up a sequence of floats to produce an output of running balances:
#!/usr/bin/env bash # example of using coprocesses with dc coproc mydc { dc; } # run process dc, calling it `mydc' # define convenience functions for writing/reading to mydc say () { echo "$1" >&"${mydc[1]}" ; } # echo 1st argument to mydc get () { read res <&"${mydc[0]}" ; } # set var `res' is response say "0" # initialise stack with 0 for v in 10.01 11.02 12.03 do say "$v + p" get echo "Val: $v, Running: $res" # produce output done say "q" # quit dc # output will be: #Val: 10.01, Running: 10.01 #Val: 11.02, Running: 21.03 #Val: 12.03, Running: 33.06
The code above is available as a gist, and also works on cygwin.