0

This is confusing me.

false || echo "Oops, fail" # Oops, fail
true || echo "Will not be printed" #
true && echo "Things went well" # Things went well
false && echo "Will not be printed" #

true return 0 exit code and false returns 1. I am unable to understand how || and && are working. Do both of them work on exit codes or the actual output of the command? What is the difference between && and || operator here?

The above code snippet is from the missing semester of your CS education lecture 2.

1
  • 4
    Yes, they both work on exit codes Commented Mar 7, 2020 at 15:17

1 Answer 1

4

x && y executes x, then only executes y if x succeeds (i.e., has an exit status of 0)

x || y executes x, then only executes y if x fails (i.e., has a non-zero exit status)

The output of x is irrelevant.

One place they do not differ is in precedence. Unlike Boolean operators in other languages, && and || have equal precedence, so something like

a || b && c

is parsed and evaluated the same as

{ a || b; } && c

rather than

a || { b && c; }

Not the answer you're looking for? Browse other questions tagged or ask your own question.