KenSchutte.com
random pic random pic random pic random pic random pic
 

 

How to make a simple Linux command-line calculator

Here's a real simple way to get calculator functionality on the linux command line. I wanted to find something where I can (from the regular bash command line) type the minimum number of keystokes possible to exectute simple mathematical expressions, and I couldn't find what I was looking for...

  • bc and dc are powerful, but require (as far as I know) fairly verbose expresssions, e.g. 'echo "1 1 + p q" | dc', 'echo "1+1" | bc'.
  • bash has 'expr', but it doesn't handle floating point numbers, and some of the syntax is annoying (e.g. 'expr 1+1' vs. 'expr 1 + 1').

Here's one solution... Create a one line perl script that just evaluates the arguments as a perl statment. I name it 'pc' for perl calculator (I want something very short). Make it executable, and move to somewhere in your path. You might be able to accomplish everything you need by just copying these commands and pasting into a command line:


echo -n "#" > pc
echo -n ! >> pc
echo "/usr/bin/perl" >> pc
echo "print eval(join(' ',@ARGV)).qq{
};" >> pc
chmod +x pc
sudo mv pc /usr/bin/

This creates a one line script in /usr/bin/pc, which looks like:


$ cat /usr/bin/pc
#!/usr/bin/perl
print eval(join(' ',@ARGV)).qq{
};

Something similar is mentioned here, but I just want to enter simple expressions from the command line, not an interactive program...

Now, you can do simple calcuations with a couple keystrokes directly from command line. (Be careful with spaces in some cases):

$ pc 1 + 3
4
$ pc 1/100 + 39
39.01
$ pc 8*2.512 / 139     # okay (in bash)
0.144575539568345
$ pc 8 * 2.512 / 139   # NOT OKAY !!! (in bash)
   # ---> tries to excute all files in . as perl commads...

Generally, spaces and more complicated things (e.g. using parantheses) require you to put quotes around the arguments:

$ pc '8 * 2.512 / 139'
0.144575539568345
$ pc '3*(5-2*(7-1))'
-21

You can of course harness any of the power of perl:


$ pc rand
0.0263503085161609
$ pc 'int(rand(100))'  # rand num on range [0,99]
14
$ pc 'sin 3.14'
0.00159265291648683
$ pc exp 1
2.71828182845905
$ pc 0xff1         # hex to decimal
4081
$ pc 0b11101100   # binary to decimal
236

Careful with some notation:

$ pc 2^10    # wrong
8
$ pc 2**10   # right
1024
© 2008 Ken Schutte