Sep 012016
 

Although I use graphical on-screen calculators for many calculations, it can sometimes be convenient to perform calculations at the command-line (or in shell scripts). In which case the old tool is expr :-

» expr 3 \* 9 
27

Very convenient; even though I can do such a calculation in my head there are circumstances where checking with a calculator is suitably cautious. You can of course perform calculations directly in the shell; if you are using a modern shell such as zsh or bash :-

» echo $((3 * 9))
27

Whilst convenient, such methods do have their disadvantages :-

  • The expr tool takes it’s expression after the shell has had it’s way with interpreting it – which is why I have escaped the “*” to multiply. You cannot put quotes around the expression either as expr assumes it to be a string.
  • These calculations are integer calculations, so you cannot find out what 77/4 is (19.25). Oops! Turns out that if you make one of the numbers in the expression a float, then the result is properly calculated: echo $((77.0/4) -> 19.25.
  • These calculators are limited to relatively small numbers – according to zsh, 2^63 is -9223372036854775808

If you need something a little more sophisticated then qalc (this is the command-line interface for Qalculate!) makes a pretty good command line calculator. It has to be installed with sudo apt-get install qalc and once installed it should be run interactively to get the initial configuration out of the way :-

» qalc
You need the download exchange rates to be able to convert between different currencies.
You can later get current exchange rates with the "exchange rates" command.
Do you want to fetch exchange rates now from the Internet (default yes)? yes
> quit

Once installed you can perform calculations in the same way as expr (although you can enclose an expression in quotes) :-

» qalc "3 * 9"
3 * 9 = 27
» qalc "2 ^ 72"
2^72 = approx. 4.7223665E21
» qalc "0xff"  
255 = 255
» qalc "86400s to hours"                                                                  
86400 * second = 24 h

You can add the “-t” option to prevent qalc telling you the expression it calculated; perhaps more useful in scripts than interactively.

damascus-unix-prompt