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: alex xmb ratchev
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 13:05:40 +0100

On Thu, Mar 23, 2023, 13:00 Greg Wooledge <greg@wooledge.org> wrote:

> 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.
>

sorry mate , but i have to write , this code on mail with declare -p , is
NOT my code

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!!
>

okk this message i got .. :))

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.
>

i know , your lil outdate ness
i in meantime finished the code , two others helped , this is the result

cpuc() {
declare -gi cpuc
 ((
! cpuc ? cpuc = $( 2>&- grep -c ^processor /proc/cpuinfo ) : 0 ,
cpuc >4 ? cpuc -=2 : cpuc >1 ? cpuc-- : ( cpuc =1 )
 ))
  }

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


reply via email to

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