2

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
4
  • 6
    This is because $var is empty in that last iteration of the loop. The file probably ends with a blank line Commented Oct 29, 2020 at 17:53
  • I don't understand how I correct it, do I end it differently? Commented Oct 29, 2020 at 18:34
  • you could check if $var is empty before using it Commented Oct 29, 2020 at 18:52
  • in the case of a blank line (ie, ${var} is undefined) you could default ${var} to 0: ${var:-0} Commented Oct 29, 2020 at 18:53

2 Answers 2

1

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"
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.