Quick-n-Dirty Math from the Shell
Tags: Perl
I find myself needing to whip out a calculator a dozen times a day, but my calculator is never at my fingertips when I need it and the “Calc” application on my BlackBerry is too clunky to use with the trackball. I needed a faster way to do some quick math when I’m around the laptops I use every day.
Did I mention I’m horrible at math? Yes, it’s true. I’ve been working with computers for the last 2 decades, and I still struggle with some intermediate and complex math concepts. But that’s why we have computers and calculators, right?
I’m used to using bc(1) for all of those quick and dirty needs, but it requires that I load it up in an interactive fashion. It looks like this:
bc in Interactive Mode
$ bc bc 1.06.94 Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. scale=3 19931424 / 1024 19464.281 quit
I have to type each line one at a time. It’s effective, but clunky because it is manual and interactive. So I started looking around for other ways to do this, that weren’t so complex and could be done non-interactively.
bc in non-interactive mode
bc(1) doesn’t have a non-interactive mode as an option, but you can pipe things into it:
Simple math using pipes:
$ echo '(2+2)' | bc 4
$ echo '7+(6*5)' | bc 37
Square root:
$ echo 'scale=30;sqrt(2)' | bc 1.414213562373095048801688724209
Convert from hexidecimal to decimal:
$ echo 'ibase=16;obase=A;FE' | bc 254
Binary to decimal:
echo 'ibase=2;obase=A;10' | bc 2
Using a redirect syntax:
$ bc -l <<< '10.5 + 1.5' 12.0
You get the idea. But as I started tinkering more with the shell, I discovered a few other ways to do simple math without using bc. If you’re using Bash as your shell, you can do math directly in the shell there as well:
Using expr(1) from Bash
$ expr 19931424 / 1024 19464
expr 2 + 2 4
Using bash itself
$ echo $[2 + 2] 4
echo $((2 + 2)) 4
Math with Perl one-liners
Simple addition:
$ perl -le 'print '2+2'' 4
Complex addition:
$ perl -le 'print 2+2+(5+100)' 109
Square root:
$ perl -le 'print sqrt(64);' 8
Pretty simple and effective, and does not require you to interact with it directly.