Bash exit status of shorthand increment notation

a++ is post-increment: it increments after the statement is evaluated. By contrast, ++a increments before. Thus:

$ a=0 ; ((a++)) ; echo $a $?
1 1
$ a=0 ; ((++a)) ; echo $a $?
1 0

In the first case, ((a++)), the arithmetic expression is evaluated first, while a is still zero, yielding a value of zero (and hence a nonzero return status). Then, afterward, a is incremented.

In second case, ((++a)), a is incremented to 1 and then ((...)) is evaluated. Since a is nonzero when the arithmetic expression is evaluated, the return status is zero.

From man bash:

   id++ id--
          variable post-increment and post-decrement
   ++id --id
          variable pre-increment and pre-decrement

Leave a Comment