Thursday, September 6, 2012

Bash Shell Calculator

Working on the Linux shell has always missed something, in my experience: an easy-to-use calculator.

Yes, there is the almighty bc, but it is everything but immediate to use. So here I'm just sharing an easy to implement wrapper to bc, which allows to easily use your shell as a calculator.

Simply drop these lines into a file called 'calc':


#!/bin/bash
echo "scale=2; $1" | bc; exit

Then simply make it executable and copy it into /usr/bin/:

$ chmod 755 calc
# mv calc /usr/bin


Then, you can start doing your math in your shell, simply like:

$calc 3/2
1.50

Consider that, if you want to use more complex operations, you have to escape any special character, like:

$ calc \(3+2\)/4
1.25

And simply change the number after "scale=" to add more precision to the results!