Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Invalid Arithmetic Operator" when doing floating-point math in bash

Here is my script:

d1=0.003 d2=0.0008 d1d2=$((d1 + d2))  mean1=7 mean2=5 meandiff=$((mean1 - mean2))  echo $meandiff echo $d1d2 

But instead of getting my intended output of:

0.0038 2 

I am getting the error Invalid Arithmetic Operator, (error token is ".003")?

like image 315
John Smith Avatar asked Feb 25 '16 17:02

John Smith


People also ask

How do you float arithmetic in Bash?

While you can't use floating point division in Bash you can use fixed point division. All that you need to do is multiply your integers by a power of 10 and then divide off the integer part and use a modulo operation to get the fractional part.

What is an invalid arithmetic operator?

syntax error: invalid arithmetic operator (error token is ...) This error is generally due to improperly formatted variables or integers used in the arithmetic expression. The most common mistake would be to try to use a floating-point number, which would fail as such.

Can you do math in Bash?

Math and arithmetic operations are essential in Bash scripting. Various automation tasks require basic arithmetic operations, such as converting the CPU temperature to Fahrenheit. Implementing math operations in Bash is simple and very easy to learn.


1 Answers

bash does not support floating-point arithmetic. You need to use an external utility like bc.

# Like everything else in shell, these are strings, not # floating-point values d1=0.003 d2=0.0008  # bc parses its input to perform math d1d2=$(echo "$d1 + $d2" | bc)  # These, too, are strings (not integers) mean1=7 mean2=5  # $((...)) is a built-in construct that can parse # its contents as integers; valid identifiers # are recursively resolved as variables. meandiff=$((mean1 - mean2)) 
like image 57
chepner Avatar answered Sep 23 '22 01:09

chepner