A simple shell calculator

As a System Engineer the command line is where I live most of the time. So having a quick means of calculating is needed.

The tool “bc” (think: binary calculator) is your friend here but you must be aware of the -l option. I often use one of two methods. For a series of calculations I will use “bc -l”.  The -l option will include the standard math libraries (my reasoning here is an over simplification: it allows floating point results).

I have an alias in my (extensive) .bashrc script that looks like this:

alias bcl="bc -l"

This allows me to quickly establish a live calculator by typing “bcl” and when I am finished hit Ctrl-D

The second method still uses “bc” but is a function in my .bashrc script called calcit. Note that within the comments I provide a way to do this in perl as well.

########
calcit() # command line calculator
########
{
# if no argument provided (we expect at least one)
if [ x$1 = "x" ] ; then
  echo Examples: calcit -s 2 \"13000 / 530000\"
  echo "   the -s 2 means set the scale to 2 decimal places"
  echo or
  echo calcit \"13000 / 530000\"
fi

# if the first argument is "-s" then grab the next arg as the desired scale
# i.e.: places past the decimal point
if [ "x$1" = "x-s" ]; then
  SCALE=$2
  shift 2
fi
SCALE=${SCALE:-1}

# now pump in the scale and the rest of the argument(s) (which we assume the is the calculation)
# into bc (-q for quiet [no welcome banner] and -l for math libraries)
bc -ql <
I can easily run a quick calculation from the command line with something like this:
calcit 70*70/105
49.6
Enjoy
-g-
This entry was posted in System Admin. Bookmark the permalink.

Leave a Reply