help-bash
[Top][All Lists]
Advanced

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

Re: whats wrong with (( a = 8 , a > 4 && a -= 2 || a-- )) , bash: ((: a


From: Greg Wooledge
Subject: Re: whats wrong with (( a = 8 , a > 4 && a -= 2 || a-- )) , bash: ((: a = 8 , a > 4 && a -= 2 || a-- : attempted assignment to non-variable (error token is "-= 2 || a-- ")
Date: Thu, 23 Mar 2023 07:59:36 -0400

On Thu, Mar 23, 2023 at 12:38:58PM +0100, alex xmb ratchev wrote:
> $ (( a = 2 , a > 1 && (a -= 2) || a-- )); declare -p a

STOP using && || as if it were an if/then/else.  It is NOT.

You think that, depending on the initial value of a, you'll either
subtract 2, or subtract 1.  This is NOT true.  In fact, you've already
chosen the correct initial value of a to SHOW that it's not true.

unicorn:~$ (( a = 2 , a > 1 && (a -= 2) || a-- )); declare -p a
declare -- a="-1"

Both subtractions are being performed, because && || is NOT AN IF/ELSE!!

If you want exactly one subtraction to be performed, you need to actually
USE if/else, or use the ternary ?: operator.

    a=2
    if ((a > 1)); then ((a -= 2)); else ((a--)); fi

or

    a=2
    (( (a > 1) ? a -= 2 : a-- ))

or

    a=2
    ((a -= (a > 1) ? 2 : 1))

?? :: is NOT a ternary conditional operator, and CANNOT be used as an
alternative.

See also <https://mywiki.wooledge.org/BashPitfalls#pf22>.



reply via email to

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