There are multiple ways to solve "Invalid Arithmetic Operator" error when trying to do floating-point math in bash. Often the errors are caused by using the wrong syntax for performing floating-point calculations.
Note that bash does not support floating-point arithmetic operations. We need to use an external utility like bc.
bc
command
In bash, we can use the bc
command to perform floating-point math. For example:
echo "4.2 + 1.2" | bc
result into:
5.4
-l
option
We can use the -l
option to enable math functions and other advanced features:
echo "sqrt(3)" | bc -l
THe output of this command is:
1.73205080756887729352
Without the option '-l' we will get result: 1
Float precision
In in order to specify the precision we can use scale
:
a=10
b=3
echo "scale=2 ; $a / $b" | bc
The result will have two decimal places:
3.33
bc is a calculator(terminal based) bundled with most distributions
Float calculation to variable
To assign the result of a floating-point calculation to a variable, you can use the $(())
operator, like this:
a=$(echo "4.2 + 1.2" | bc)
syntax error: invalid arithmetic operator
The error can be reproduced by the following bash script:
a=4.2
b=1.2
ab=$((a + b))
Which raise an error:
bash: 4.2: syntax error: invalid arithmetic operator (error token is ".2")
awk to calculate floating numbers
As alternative solution for floating-point math in Bash we can use command awk
:
a=4.2
b=1.2
echo "$a $b" | awk '{print $1 - $2}'
result is:
3