I'm working through some basic exercises using Bash and I'm confused on the order of operations of &&
and ||
. Below are some reproducible examples.
# Example 1
true && false || echo pass
# pass
Since the first true
is executed, &&
passes on to false
and false
is executed (true && false
). ||
evaluates false
and since there's a false
on the left hand side, echo pass
gets executed (false || echo pass
). So far so good.
Example 2
false && false || echo pass
# pass
Since the first expression is false
, &&
does not execute the second false
. However, echo pass
gets printed because the left hand side of false || echo pass
is false. All is good so far.
Example 3
[[ 2 -gt 3 ]] && echo t || echo f
# f
2
is not greater than 3
, meaning that echo t
doesn't get executed. However, echo t || echo f
prints f
. Based on the previous two examples, echo t
should return a non-exit code and don't execute echo f
on the right hand side.
What am I missing?
echo t || echo f
on its own printsf
? It printst
.false && true || echo pass
which I think would invalidate the misconception you're having.&&
and||
in a single list (at least, not without explicit grouping with{ ... }
and proper guarding of the exit status for the "if" block). Use anif
statement instead.