Difference between executing multiple commands with && and ;

In the shell, && and ; are similar in that they both can be used to terminate commands. The difference is && is also a conditional operator. With ; the following command is always executed, but with && the later command is only executed if the first succeeds.

false; echo "yes"   # prints "yes"
true; echo "yes"    # prints "yes"
false && echo "yes" # does not echo
true && echo "yes"  # prints "yes"

Newlines are interchangeable with ; when terminating commands.


&& and || are boolean operators. && is the logical AND operator, and bash uses short cut evaluation, so the second command is only executed if there is the chance that the whole expression can be true. If the first command is considered false (returned with a nonzero exit code), the whole AND-expression can never become true, so there is no need to evaluate the second command.

The same logic applies analogously to the logical OR, ||: if the first command is successful, the whole OR-expression will become true, so no need to evaluate the second command.

Tags:

Shell

Bash