Score:4

"invalid arithmetic operator" error when trying to add variables in Bash script

bd flag

Coming from a Python background, this is my first simple Bash script and it does not work. I'm confused.

#!/bin/bash
RTCHOST='192.168.0.143'
PANEL1=$(client read-value --host $RTCHOST --name dc_1)
echo Panel1: $PANEL1
PANEL2=$(client read-value --host $RTCHOST --name dc_2)
echo Panel2: $PANEL2
PANELCONSUMPTION=$(($PANEL1 + $PANEL2))
echo Consumption: $PANELCONSUMPTION

When I run the script, I get a syntax error:

invalid arithmetic operator

What's wrong?

Score:6
uy flag

I guess $PANEL1 and $PANEL2 are floating point numbers. However, Bash is only capable of handling integers, not floating point numbers, as explained in Arithmetic Expansion. If you try to sum floating point numbers, you will get the invalid arithmetic operator error.

Simply try it here:

#!/bin/bash
A='5'
B='6.4'
C=$(($A + $B))
echo $C

Adding floating point numbers is described in this Stack Overflow thread: How can I add numbers in a Bash script?

In essence, you can use an external utility, such as bc, to do the operation as shown in this example:

#!/bin/bash
A='5'
B='6.4'
C=$(echo $A + $B | bc) 
echo $C

This works and returns the expected value of 11.4.

Peter Cordes avatar
fr flag
`echo $A + $B` should probably be `echo "$A + $B"` for good measure; no reason to do unquoted expansion of those variables. Unless you need to eat newlines that might mess up `bc`, if they came from capturing `$(command substitution)`.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.