I'm looking for a way to do quick calculations in the terminal (using utilities available in Ubuntu minimal) and get accurate fail errors when the math syntax is incorrect, eg: cli-calculator "foo+bar" || echo invalid math syntax
Some of the inputs would be:
1+1 #should print 2 and return a 0 code
5/2 #should print 2.5 and return a 0 code
1/0 #should return a non 0 code
foo+bar #should return a non 0 code
I've tried bc
, shell integrated arithmetic, expr
, awk
, perl
and python
but so far none has satisfied fully my requirements, so I'm looking for alternatives, follow use cases:
bc
, it's able to do operations with float numbers but doesn't return error codes on invalid syntax input$ echo "1/0" | bc -l && echo all is fine || echo math syntax error Runtime error (func=(main), adr=3): Divide by zero all is fine $ echo "foo+bar" | bc -l && echo all is fine || echo math syntax error 0 #should return an error all is fine
Shell integrated arithmetic and
expr
, don't support operations with float numbers and return valid codes on invalid math input$ echo $((5/2)) 2 #should return 2.5 $ echo $((foo+bar)) 0 #should return an error $ expr 5 / 2 2 #should return 2.5 $ expr foo+bar foo+bar #should return an error
awk
|perl
, don't return invalid status codes on invalid math input.$ awk "BEGIN {print foo+bar; exit}" 0 #should return a non 0 number and probably output an error $ echo "foo+bar" | perl -ple '$_=eval' 0 #should return a non 0 number and probably output an error
python
, supports float arithmetic operations and return status errors on invalid math syntax but it's slow.$ python -c 'from __future__ import division; from math import *; print(foo+bar)' && echo all fine || echo math syntax error NameError: name 'foo' is not defined math syntax error #good! $ python -c 'from __future__ import division; from math import *; print(5/2)' && echo all fine || echo math syntax error 2.5` #good! all fine
Any ideas?
What about
calc
Examples
Or
qalc
bc
And this is correct, 0 + 0 is 0
Or
gcalccmd
, the console version ofgnome-calculator
the calculator of the GNOME desktop environment.Examples
Note that
gcalccmd
does not have readline support, so only the most basic line editing features are available. (Backspace works, but left/right keys don't)Octave is another alternative. It is a very powerful free tool with a syntax 'like the commercial tool matlab'. If you want to run it without a gui, use the option
--no-gui
or the commandoctave-cli
.Example based on your 'valid and invalid' expressions: