Confusing use of && and || operators

The right side of && will only be evaluated if the exit status of the left side is zero (i.e. true). || is the opposite: it will evaluate the right side only if the left side exit status is non-zero (i.e. false).

You can consider [ ... ] to be a program with a return value. If the test inside evaluates to true, it returns zero; it returns nonzero otherwise.

Examples:

$ false && echo howdy!

$ true && echo howdy!
howdy!
$ true || echo howdy!

$ false || echo howdy!
howdy!

Extra notes:

If you do which [, you might see that [ actually does point to a program! It's usually not actually the one that runs in scripts, though; run type [ to see what actually gets run. If you wan to try using the program, just give the full path like so: /bin/[ 1 = 1.


Here's my cheat sheet:

  • "A ; B" Run A and then B, regardless of success of A
  • "A && B" Run B if A succeeded
  • "A || B" Run B if A failed
  • "A &" Run A in background.

to expand on @Shawn-j-Goff's answer from above, && is a logical AND, and || is a logical OR.

See this part of the Advanced Bash Scripting Guide. Some of the contents from the link for user reference as below.

&& AND

if [ $condition1 ] && [ $condition2 ]
#  Same as:  if [ $condition1 -a $condition2 ]
#  Returns true if both condition1 and condition2 hold true...

if [[ $condition1 && $condition2 ]]    # Also works.
#  Note that && operator not permitted inside brackets
#+ of [ ... ] construct.

|| OR

if [ $condition1 ] || [ $condition2 ]
# Same as:  if [ $condition1 -o $condition2 ]
# Returns true if either condition1 or condition2 holds true...

if [[ $condition1 || $condition2 ]]    # Also works.
#  Note that || operator not permitted inside brackets
#+ of a [ ... ] construct.