Over the years I have written many script libraries to handle arithmetic functions, some of them quite messy involving determing where the decimal point is in the string, removing it, adjusting other strings, doing the calculations using the bash inbuilt functions, and reinserting the decimal point into the string afterward.
And then I found a tiny post on lifehacker.com.au today (lifehacker attributed it to TinyHacker), a simple one line function using awk could do it all.
The post simply was add to your .bashrc the line
calc(){ awk “BEGIN{ print $* }” ;}
damn, it just works
[mark@osprey ~]$ calc 10/3
3.33333
[mark@osprey ~]$ calc “(2^3)+1”
9
However Its not too pretty if you forget quotes and are using * in the arithmetic expression. And spaces seemed to cause problems if they were in some places in the arethmetic equation, so I changed the function slightly for my .bashrc to ensure all spaces were removed; my function is below. It’s still a one line function, I just comment things :-).
calc() {
# function: command line calculator, using awk
# syntax: calc “arithmetic expressions” <--- use quotes
# example: mark@falcon ~]$ calc "(100*(2^3) - 600) / 3"
# 66.6667
#
# nasty things can happen if spaces are included, remove them all
echo "$*" | sed -e"s' ''g" | awk "BEGIN{ print $* }"
}
Unfortunately I can't test for quotes in the function, as all the expansion of wildcards is done by the shell before the function is invoked, so it's not bulletproof.
However it looks like might be archiving my script math libraries now