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}"
Looks fine? I've probably written this many times. There's a small gotcha:
((expression)) The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. 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”.
When you run this script with -e or enable errexit – probably because the script has become too big to be reliable without it – count++ is going to return 0 (post-increment) and per above stop the script. A definite trap to watch out for!
bash/arithmetic_evaluation_and_errexit_trap.1575682380.txt.gz · Last modified: 2020/07/15 09:30 (external edit)