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 :
echo this || echo that && echo other
implies true || true && true
&&
has more precedence
than ||
, the second expression evaluates firstboth are true
, the ||
is evaluated which also gives true.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!
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With