Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does AND and OR operators work in Bash?

Tags:

bash

shell

I tried the following command on bash

echo this || echo that && echo other

This gives the output

this
other

I didn't understand that!

My dry run goes this way :

  1. echo this || echo that && echo other implies true || true && true
  2. Since, && has more precedence than ||, the second expression evaluates first
  3. Since, both are true, the || is evaluated which also gives true.
  4. Hence, I conclude the output to be:

that

other

this

Being from a Java background where && has more precedence than ||, I am not able to relate this to bash.

Any inputs would be very helpful!

like image 986
TechSpellBound Avatar asked Feb 12 '13 16:02

TechSpellBound


3 Answers

From man bash

3.2.3 Lists of Commands

A list is a sequence of one or more pipelines separated by one of the operators ‘;’, ‘&’, ‘&&’, or ‘||’, and optionally terminated by one of ‘;’, ‘&’, or a newline.

Of these list operators, ‘&&’ and ‘||’ have equal precedence, followed by ‘;’ and ‘&’, which have equal precedence.

So, your example

echo this || echo that && echo other

could be read like

(this || that) && other
like image 153
Olaf Dietsche Avatar answered Oct 06 '22 23:10

Olaf Dietsche


In bash, && and || have equal precendence and associate to the left. See Section 3.2.3 in the manual for details.

So, your example is parsed as

$ (echo this || echo that) && echo other

And thus only the left-hand side of the or runs, since that succeeds the right-hand side doesn't need to run.

like image 31
unwind Avatar answered Oct 07 '22 00:10

unwind


Boolean evaluation in bash is short-circuit: true || false will never evaluate the false operand, because the true operand is enough to determine the outcome of the operation. Likewise, false && true will not evaluate the true operand, because it cannot change the value of the expression.

Boolean evaluation in bash is actually used mainly for controlling the conditional evaluation of the operands, not their order. Typical usage is do_foo || do_bar_if_foo_fails or do_foo && do_bar_only_if_foo_has_succeeded.

In no situation will your echo that command be executed, because the echo this is true and determines the value of the entire echo this || echo that sub-expression.

like image 24
lanzz Avatar answered Oct 07 '22 01:10

lanzz