Table of Contents

BASH - Math - Error with ((expression))

WARNING: Be careful when using ((expression)).


Arithmetic evaluation and errexit trap

count=0
things="0 1 0 0 1"
 
for i in $things;
do
  if [ $i == "1" ]; then
    (( count++ ))
  fi
done
 
echo "Count is ${count}"

returns:

2

Check the return code

echo $?

returns:

0

NOTE: A 0 indicates success.

A 1 indicates failure.

NOTE: This looks fine; but there is a small gotcha:

The ((expression)) is evaluated according to the Arithmetic Evaluation rules.

  • If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1.
  • This is exactly equivalent to let “expression”.

But if you run this script with -e or enable errexit:

bash -e test.sh

then count++ is going to return 0 (post-increment) and the script will stop.

Checking the result:

echo $?

returns:

1

This time a failure.

A definite trap to watch out for! Do not use ((expression)) here.