[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Precedence of || and &&
From: |
Eduardo Bustamante |
Subject: |
Re: [Help-bash] Precedence of || and && |
Date: |
Tue, 3 Jan 2017 23:58:05 -0600 |
On Tue, Jan 3, 2017 at 8:19 PM, Peng Yu <address@hidden> wrote:
[...]
> ~$ true || false && false
> ~$ echo $?
> 1
Instead of precedence, I think you're asking about operator
associativity (https://en.wikipedia.org/wiki/Operator_associativity),
that is, given:
A x B x C, where A, B & C are commands, and 'x' are boolean operators,
how does that expression associate? Is it: (A x B) x C, is it A x (B x
C), are these two expressions equivalent?
If you refer to the POSIX standard document describing the "Shell
Command Language", section 2.9.3 "Lists"
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_03
The operators "&&" and "||" shall have equal precedence and shall
be evaluated with left associativity. For example, both of the
following commands write solely bar to standard output:
false && echo foo || echo bar
true || echo foo && echo bar
So, these are left associative (A x B x C associates as (A x B) x
C). With that in mind, your example:
true || false && false is associated as (true || false) && false
which of course reduces to true && false which then reduces to
false. Therefore $? = 1
That is, if we operate only in terms of boolean commands like true /
false. I'd avoid complexity in such lists by following the advice in
http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Control_Operators_.28.26.26_and_.7C.7C.29