On Fri, Jun 13, 2025 at 12:41:16 +0300, Stamatis Mavrogeorgis wrote:
> The shorthands "++", "--", "+=1" and "-=1" in bash arithmetic
> erroneously return exit code 1 when a variable is either incremented by
> "++" or decremented by "--" from 0 or incremented by "+=1" or decremented
> by "-=1" from -1 and 1 respectively, although the variable value changes
> properly.
That's not a bug. That's a design feature.
The exit status of an arithmetic command is 0 (true) is the result of
the arithmetic expression is non-zero. The exit status is 1 (false)
if the expression is zero.
This mimics the logic of the C language. It's intentional. It allows
you to write code like:
if ((a > 2)); then
...
In that case, the expression a > 2 is evaluated, and is either true,
in which case the expression evaluates to 1 and the exit status is 0,
or false, in which case the expression evaluates to 0 and the exit
status is 1.
Because that's how C does things.
By the same logic, an arithmetic command like
((a = 1))
is also an expression whose value is 1, and therefore the exit status
is 0. Likewise,
((a = 0))
is an expression whose value is 0, and therefore the exit status is 1.
hobbit:~$ if ((a = 0)); then echo yes; else echo no; fi
no
hobbit:~$ if ((a = 1)); then echo yes; else echo no; fi
yes
All of this is intentional, and not a bug.
See also <https://mywiki.wooledge.org/BashFAQ/105#Exercises>.