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")?
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With