Unix Command Line Calculator

I spend a lot of time on a Linux / Unix command line. Often I need to do a quick calculation. I don’t want to hunt around for a fancy calculator program. I want something that works right from the command line.

The bc program is a command line calculator for Linux / Unix. It is an arbitrary precision calculator, and it can even be programmed in a simple language. Read the man page for a complete list of what it can do.

Now, most of the time I just need a simple calculation done. For this purpose I have written a small program called ‘c’ (for calculate):

#!/usr/local/bin/tcsh -f
echo "$*" | bc -l

Yes, it is just two lines. You could also define it as an alias in tcsh:

alias c 'echo \!* | bc -l'

Or as a function in bash:

function c() { echo "$*" | bc -l; }

Now, to do a simple calculation on the command line, you just write:

c "1+2*3"

And you get the result 7.

It will also allow you to do more advanced math. For example, “s” for sine, “c” for cosine, and “e” for the exponential function, and “l” for the natual logarithm:

c "e(5)"
c "s(0)"
c "c(3.1415)"
c "l(e(5))"

I believe the bc program is part of Cygwin (the Linux / Unix environment for Microsoft Windows), so you should be able to get it to run on your Windows computer as well.

, , ,

One Response to “Unix Command Line Calculator”

  1. NiftyGuy August 19, 2008 at 5:55 pm #

    Tell us about calculating on Google!

Leave a Reply