Bash’s conditional operator and assignment

arithmeticbashshellshell-script

Can we use bash's conditional operator with assignment operators after colon?

Bash reference manual explains the arithmetic operators as follows.

  • conditional operator expr ? expr : expr
  • assignment = *= /= %= += -= <<= >>= &= ^= |=

First, this code seems to work well:

a=1; ((a? b=1 : 2 )) #seems to work

But when I use assignment operators after :, I got 'attempted assignment to non-variable' error:

a=1; ((a? b=1 : c=1)) #attempted assignment to non-variable error

Why can we use only assignment operators before colon?

Best Answer

Bash parses your last command as

a=1; (( (a? b=1 : c)=1 ))

which should make clear why it does not work. Instead you have to use

a=1; (( a? b=1 : (c=1) ))