The following script with debug option set -e -v
fails at the increment operator only when the variable has a prior value of zero.
#!/bin/bash
set -e -v
i=1; let i++; echo "I am still here"
i=0; let i++; echo "I am still here"
i=0; ((i++)); echo "I am still here"
bash (GNU bash, version 4.0.33(1)-release (x86_64-apple-darwin10) but also GNU bash, version 4.2.4(1)-release (x86_64-unknown-linux-gnu))
Any ideas?
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.