User Tools

Site Tools


bash:arithmetic_evaluation_and_errexit_trap

This is an old revision of the document!


BASH - 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!

bash/arithmetic_evaluation_and_errexit_trap.1610203148.txt.gz · Last modified: 2021/01/09 14:39 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki