Skip to content
Advertisement

bash order-of-operations in math context: Wrong value assigned

Given the linux shell code,

~$ (( b = a, (a += 3) + $((a = 1)), b++ ))
~$ echo $b
2

Why does $b equal 2? I split the code into three steps:

~$ ((b = a))
~$ (((a += 3) + $((a = 1))))
~$ ((b++))
~$ echo $b
1

$b equals 1 this time, why?


P.S. Neither a nor b is initialized.

Advertisement

Answer

Because you set b = a, then bash waits for last assigning of a. In b will be assigned same value as the value assigned to a.

~$ (( b = a, (a += 3) + $((a = 5)), b++ ))
~$ echo $b
6
~$ echo $a
8

EDIT

1) column-separated expressions are treated sequentially

~$ echo $((1+1, 2+2, 3+3))
6

2) $((...)) expressions are treated first

which gives result:

(( b = a, (a += 3) + $((a = 1)), b++ ))
  1. $((a = 1)) #a=1
  2. b = a #a=b=1
  3. a += 3 #a=4, b=1
  4. b++ #a=4, b=2
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement