Syntax error: operand expected (error token is "+)

Viewed 1181

I am getting this error message: line 12: 470 + : syntax error: operand expected (error token is "+ ")

I still get my answer of 470 at the end but this error message display in the output and I cannot understand why. Can any one please explain?

Here is my code:

while IFS= read -r var
do
total=$(($total+$var))
done<"$input"

 

echo "The total is = $total";
echo

My final output each time:

 line 12: 470 + : syntax error: operand expected (error token is "+ ")
The total is = 470
2 Answers

When you use a $ with a dereference inside an arithmetic expression, that prevents special arithmetic parsing rules (that treat an empty string as a 0) from being able to apply. Just take out the $s on the inside to fix your problem:

while IFS= read -r var; do
  total=$((total+var))
done <"$input"

...or, for clearer (but bash-only) syntax:

while IFS read -r var; do
  (( total += var ))
done <"$input"

Based on other comments, I would change to this to ignore empty lines and whitespace. I don't have your $input file, so I am just entering data directly in the shell and ending my data entry with the EOF indicator (<CTRL>d for me)

$ total=0;while IFS= read -r var; do [[ -n "${var##*\ }" ]] && total=$(($total+$var)) ; done

1

2
3

^D
$ echo ${total}
6
Related