coprocesses in bash using dc as an example

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.

Advertisements

About mcturra2000

Computer programmer living in Scotland.
This entry was posted in Computers, Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s