This caught me by surprise: applying the post-increment operator
(++
) to a zero value variable results in a non-zero result code.
That is, given:
#!/bin/bash
myvar=0
let myvar++
echo "result: $?"
Running that (with bash 5.1.0) results in:
result: 1
Why does that produce a nonzero result code? We see the same behavior using a numeric expression:
#!/bin/bash
myvar=0
(( myvar++ ))
echo "result: $?"
On the other hand, if we use +=
instead of ++
, or if we start with
a nonzero value of myvar
, we receive a 0 result code as expected. The
following...
myvar=1
let myvar+=1
echo "result: $?"
myvar=1
let myvar++
echo "result: $?"
myvar=1
(( myvar++ ))
echo "result: $?"
...all produce:
result: 0
What's going on here?