LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bash man not followed: ((?:)) requires paranthesis on third operand to accept vars (https://www.linuxquestions.org/questions/linux-newbie-8/bash-man-not-followed-requires-paranthesis-on-third-operand-to-accept-vars-891264/)

doru 07-12-2011 05:52 AM

bash man not followed: ((?:)) requires paranthesis on third operand to accept vars
 
Code:

echo $((myvar<5?myvar=7:myvar=myvar-1))
does not work,
Code:

echo $((myvar<5?myvar=7:(myvar=myvar-1)))
works. This is also documented here: http://www.scribd.com/doc/51950177/440/Logic (scroll down two pages).

Am I right, is this really a bug?

In fact, it requires parantheses on the third operand to accept var=.

grail 07-12-2011 08:39 AM

No it is not a bug. Did you read the error messages from your first code?
You are missing he point that this construct is being strict about what it is doing.
You can look at your first one like so:
Code:

echo $((myvar<5?myvar=7:myvar=myvar-1))
Everything in blue is part of the construct ?:, so once completed it then looks at the information in red which as it is an assignment it cannot
be assigned to an expression.

Your second version of course overcomes this by placing parenthesis around the assignment and hence it is performed prior to returning the value.

Strictly speaking you did not have to go through all this anyway:
Code:

echo $((myvar = myvar<5?7:--myvar))

doru 08-15-2011 07:17 AM

Quote:

Originally Posted by grail (Post 4412643)
No it is not a bug.

Thank you for your answer. It helps me understand what is going on.

Still I don't understand why is "=" not treated just like any other operator, for example like "<" or "--", since they do belong to the same list under "ARITHMETIC EVALUATION" in bash man. What makes ?: end before it meets "))"?

"?:" has higher precedence than "=".

grail 08-15-2011 07:59 AM

Maybe this table can help.

Ultimately each part of the trinary operator must be complete, but you will see from the table that the '=' is lower in precedence


All times are GMT -5. The time now is 09:09 PM.