Tuesday, April 03, 2012

Make Your Own Command-line Calculator with bc

I do not know about you, but I am bothered by the lack of a proper command line calculator for doing small single line calculations in Linux (or any other UNIX or Mac system). Sure bc is there but it does not support floating point by default, so one ends up writing things like:
echo "scale=3; 22/7" | bc
which is quite cumbersome for day to day work.

To subvert this trouble, I wrote the following two-liner and saved it as "calc" in a directory in PATH:
#! /bin/bash
echo "scale=3; $1" | bc; exit
Then do a "chmod +x" on the file to give it execute permission. This does the same thing as the above script, but is way simpler to use:
calc 22/7
The command "scale=3" was to instruct bc to print upto 3 decimal digits. You can change it as per your requirements.

The bc utility can do way more than this simple calculations. For example it can handle different bases and load functions from files. To know more about its capabilities try the good old "man bc" in terminal or read an online reference like this one on about.com.  You can read more about its advanced capabilities from an old but quite relevant article in LinuxJournal "bc: a handy utility".

Disclaimer : Although the script was by me, the idea is not new. In fact a lot of my colleagues use similar scripts for their own daily work.


No comments:

Post a Comment

I'd love to hear from you !