Discussion:
[Help-bash] Precedence of || and &&
Peng Yu
2017-01-04 02:19:49 UTC
Permalink
Hi, The following example shows that || and && run in the order in the
command. Is it so?

~$ true || false && false
~$ echo $?
1
~$ true || (false && false)
~$ echo $?
0
--
Regards,
Peng
Eduardo Bustamante
2017-01-04 05:58:05 UTC
Permalink
On Tue, Jan 3, 2017 at 8:19 PM, Peng Yu <***@gmail.com> wrote:
[...]
Post by Peng Yu
~$ 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
Greg Wooledge
2017-01-04 13:06:55 UTC
Permalink
Post by Peng Yu
Hi, The following example shows that || and && run in the order in the
command. Is it so?
Yes.

You should NOT mix && and || in the same command. See
http://mywiki.wooledge.org/BashPitfalls#cmd1_.26.26_cmd2_.7C.7C_cmd3
Loading...