[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: increment & decrement error when variable is 0

From: Ilkka Virta
Subject: Re: increment & decrement error when variable is 0
Date: Tue, 24 Nov 2020 10:08:18 +0200

On Tue, Nov 24, 2020 at 12:07 AM Jetzer, Bill <jetzerb@svaconsulting.com>

>                                 ((--x)) || echo "err code $? on --x going
> from $i to $x";
> err code 1 on ++x going from -1 to 0

That's not about --x, but of the ((...)) construct:

"" (( expression ))
The arithmetic expression is evaluated according to the rules described
below (see Shell Arithmetic). 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" See Bash Builtins, for a full description of
the let builtin.""

Note the second sentence and try e.g.:

$ if (( 100-100 )); then echo true; else echo false; fi

That also matches how truth values work in e.g. C, where you could write if
(foo) { ... } to test if foo is nonzero.
Also, consider the return values of the comparison operators. The behaviour
here makes it possible to implement
them by just returning a number, instead of having to deal with a distinct
boolean type that would affect the exit status:

$ (( a = 0 < 1 )); echo $a

> err code 1 on x++ going from 0 to 1

As to why you get this here, when going to one instead of zero, remember
the post-increment returns the original value.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]