Subtract two variables in Bash
You can use:
((count = FIRSTV - SECONDV))
to avoid invoking a separate process, as per the following transcript:
pax:~$ FIRSTV=7
pax:~$ SECONDV=2
pax:~$ ((count = FIRSTV - SECONDV))
pax:~$ echo $count
5
You just need a little extra whitespace around the minus sign, and backticks:
COUNT=`expr $FIRSTV - $SECONDV`
Be aware of the exit status:
The exit status is 0 if EXPRESSION is neither null nor 0, 1 if EXPRESSION is null or 0.
Keep this in mind when using the expression in a bash script in combination with set -e which will exit immediately if a command exits with a non-zero status.
This is how I always do maths in Bash:
count=$(echo "$FIRSTV - $SECONDV"|bc)
echo $count
Try this Bash syntax instead of trying to use an external program expr
:
count=$((FIRSTV-SECONDV))
BTW, the correct syntax of using expr
is:
count=$(expr $FIRSTV - $SECONDV)
But keep in mind using expr
is going to be slower than the internal Bash syntax I provided above.