[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: arithmetic evaluation : no assignment
From: |
Greg Wooledge |
Subject: |
Re: arithmetic evaluation : no assignment |
Date: |
Fri, 8 Nov 2024 09:19:19 -0500 |
On Fri, Nov 08, 2024 at 11:32:07 +0100, watael rocketmail via wrote:
> hi,
>
> a=1; b=2 #no c
> echo $(( c=$b-$a , $c>$a+$b ? $c-$a : $c+$b ))
> bash: c=2-1 , >1+2 ? -1 : +2 : syntax error: operand expected (error token
> is ">1+2 ? -1 : +2 ")
>
> I don't remember this didn't work.
As xmb pointed out, if you remove the $ signs inside the arithmetic
context, then it works.
The reason it's failing is because $a, $b and $c are all expanded
before any of the arithmetic is done. So you end up with the expression
shown in bash's error message, with nothing on the left hand side
of the > sign.
Without the $ signs, the variables are expanded *during* the arithmetic
evaluation, instead of before. And in that context, a variable that's
empty or unset is treated as if it were 0. (Though in your case, the
variable c is no longer unset at the time > is used.)
Compare:
hobbit:~$ c=6
hobbit:~$ echo $(( c=5, c*2 ))
10
hobbit:~$ c=6
hobbit:~$ echo $(( c=5, $c*2 ))
12
In the second one, $c is expanded while c is still 6. In the first one,
c is expanded after it has been changed to 5. The second one also gives
an error if c is unset prior to the $(( )) expansion, just as your
original code does.
hobbit:~$ unset c
hobbit:~$ echo $(( c=5, $c*2 ))
bash: c=5, *2 : syntax error: operand expected (error token is "*2 ")