Just like &&
, ||
is a bash control operator:
&&
means execute the statement which follows only if the preceding statement executed successfully (returned exit code zero).
||
means execute the statement which follows only if the preceding statement failed (returned a non-zero exit code).
Some of the other control operators are:
&
means execute the preceding statement in the background.
;
means execute the preceding statement and, after it completes, proceed to the next statement.
|
means execute the preceding statement and connect its stdout the to stdin of the statement which follows.
Combining &&
and ||
&&
and ||
can be combined to make an alternative to if-then-else. Consider:
if some_command
then
echo yes
else
echo no
fi
The above is similar to:
some_command && echo yes || echo no
I said "similar" rather than identical because the two are different in the case that the echo yes
command fails. If the echo yes
command were to fail (exit with a non-zero return code) then the echo no
command is executed. This would not happen with the if-then-else-fi
version. The echo
command will only fail, though, if there is a write-error on the terminal. Consequently, this difference rarely matters and the &&
and ||
form is often used as a short-cut.