matthiash
matthiash

Reputation: 3233

Numeric test when using the conditional operator

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")

Upvotes: 0

Views: 586

Answers (1)

Matthew Flaschen
Matthew Flaschen

Reputation: 284836

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.

Upvotes: 2

Related Questions