Increment operator does not work on a variable if variable is set to 0
Solution 1:
With credit from here: https://unix.stackexchange.com/questions/146773/why-bash-increment-n-0n-return-error
The return value of (( expression )) does not indicate an error status, but, from the bash manpage:
((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".
In ((a++))
you are doing a post increment. The value of a
is 0
so 1
is returned, after that, it is incremented.
Compare
$ unset a
$ ((a++)) ; echo Exitcode: $? a: $a
Exitcode: 1 a: 1
versus
$ unset a
$ ((++a)) ; echo Exitcode: $? a: $a
Exitcode: 0 a: 1
A pre-increment, so a
has become 1
and 0
is returned.
Solution 2:
This works for me (in bash
in Ubuntu),
$ a=0
$ echo $((a++))
0
$ echo $((a++))
1
$ echo $((a++))
2
$ echo $((a++))
3
$ echo $a
4
Notice the difference with
$ a=0
$ echo $((++a))
1
$ echo $((++a))
2
$ echo $((++a))
3
$ echo $a
3