tags:

views:

24

answers:

1

In bash, why doesn't this work:

$ echo $((1 -gt 2 ? 3 : 4))
bash: 1 -gt 2 ? 3 : 4: syntax error in expression (error token is "2 ? 3 : 4")

Neither does this:

$ echo $(((1 -gt 2) ? 3 : 4))
bash: (1 -gt 2) ? 3 : 4: missing `)' (error token is "2) ? 3 : 4")
+2  A: 

Use:

if [ 1 -gt 2 ]; then
  echo 3
else 
  echo 4
fi

Or:

echo $((2 > 1 ? 1 : 0))

The -gt family is used by the test command, while the operators allowed in $(()) are described here and here. You can't mix and match.

Note from the standard that "only signed long integer arithmetic is required." You need to use bc.

Matthew Flaschen
Ok, but why doesn't this work: echo $((1>2.1 ? 3 : 4))
lupuslupus
Because bash doesn't support floating point. Use the bc command.
Matthew Flaschen
Thanks a lot, everything is clear now!
lupuslupus