2008-03-11

UNIX Tip of the day: shell math with bc

bc is "an arbitrary-precision calculator language" which so happens to be nearly ubiquitous across all UNIX platforms that I've ever run across. 


Why on earth would you want to do math on the command-line?  Well, that's a good question.  I often find myself using it when I have a terminal window open and don't feel like finding a calculator or firing up the calculator program just to do some basic division or multiplication.  Remember, I suck at doing math in my head unless it's stupidly simple stuff.

What does "arbitrary precision" mean, exactly?  Well, it means that bc will only be as precise (with floating points) as you are with your input.  Integers in, integers out!

axon$ bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
491003798 * 2
982007596

This is important when doing division:
5/2
2

5 divided by 2 is obviously not 2. Set the scale to 2 to make it precise to two decimal points, and try again:
scale=2
5/2

2.50

Much better.

Like shells, you can combine multiple commands on one line with a semicolon between commands: FYI: sqrt(x) gives you the Square Root of x and x^y gives you x to the power of y. This is similar to how many scientific calculators or Google Calculator works. In fact, most of Google Calc's syntax works quite well in bc.

scale=0; sqrt (982007596); 16^2
31337
256


Since bc operates on standard input, you can use any of the below methods to do non-interactive math from the command-line or shell scripts:

Pipe:
axon$ echo "2008 * 42" | bc
84336

Here Document:
axon$ bc << EOF
> (2008 * 42) + 65535
> EOF

149871

Use bc if you are writing a shell script that requires floating-point operations, as most shells don't handle math too well. You can even use shell variables.

axon$ export gallons=12.5
axon$ export price=3.879
axon$ echo "A tank of gasoline costs \$`echo "$gallons * $price" | bc`"
A tank of gasoline costs $48.487

Note that while bc exists as part of most UNIX installations (I think it's part of the Single UNIX Specification), that the supported syntax varies between platforms a little bit.  When in doubt, check the man page.

blog comments powered by Disqus