The mentioned solutions are fine for very simple calculations, but very error-prone. Examples:
# without spaces 20+5expr literally20+5 produces literally 20+5
expr 20+5
→ 20+5
# bc's result doesn't give the fractional part by default
bc <<<
9.0/2.0
→ 4
# expr does only integer
expr 9 / 2
→ 4
# same for POSIX arithmetic expansion
echo $((9/2))
→ 4
# bash arithmetic expansion chokes on floats
echo $((9.0/2.0))
→ bash: 9/2.0: syntax error: invalid arithmetic operator (error token is ".0")
# Most `expr` implementations also have problems with floats
expr 9.0 / 2.0
→ expr: non-integer argument
A syntax error like the last ones never get unnoticedis easily noticed, but integer responses with a discarded float part can easily getgo unnoticed and lead to wrong results.
That's why I always use a scripting language like Lua for that. But you can choose any scripting language that you're familiar with. I just use Lua as an example. The advantages are
- a familiar syntax
- familiar functions
- familiar caveats
- flexible input
- spaces usually don't matter
- floating point output
Examples:
lua -e "print(9/2)"
→ 4.5
lua -e "print(9 / 2)"
→ 4.5
lua -e "print(9.0/2)"
→ 4.5
lua -e "print (9 /2.)"
→ 4.5
lua -e "print(math.sqrt(9))"
→ 3