bash set -e and i=0;let i++ do not agree

the answer to my question is not to use let (or shift, or…) but to use

i=$((i+1))

when trying to check a bash script by setting ‘exit on non-zero status code‘ with

set -e

The bash manual states that set -e has the effect of ‘Exit immediately if a simple command exits with a non-zero status.‘.

Unfortunately let (and shift and …) return the result of the computation (‘If the last arg evaluates to 0, let returns 1; 0 is returned otherwise‘). So instead of a status code one gets a return value of some sort. And sometimes this return value will be zero and sometimes one depending on the computation. Therefore set -e will cause the script to exit depending on the result of your computation!!! and there is nothing to do about it unless either you don’t use it ever or resort to

let i++ || true

as pointed by arnaud576875 which btw adds extra CPU burden.

Using

let ++i

works only for the specific case that i is not -1, as with let i++ which works only for when i is not 0. Therefore half-solutions.

I love Unix though, I wouldn’t have it any other way.

Leave a Comment