34

This question already has an answer here:

What's the difference between executing multiple commands with && and ;?

Examples:

echo "Hi\!" && echo "How are you?"

and

echo "Hi\!"; echo "How are you?"

marked as duplicate by Gilles bash Oct 6 '14 at 20:09

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 5
    Don't agree on the duplicate. That question doesn't even mention ; at all, nor do any of the answers. – Patrick Nov 11 '13 at 3:32
  • @Patrick - I understand you disagreeing, but I still think it's a dup. It talks about everything this one does, and though it doesn't specifically mention ; the meaning of ; is implied, since it's the alternative. – slm Nov 11 '13 at 6:17
  • 5
    @slm I don't agree that the meaning of ; is implied. For people that are familiar with programming, sure. But for newcomers? Not so much. – Zach Latta Nov 11 '13 at 7:01
43

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.

  • 6
    || is the opposite of &&: the RHS is executed if the LHS does not succeed: false || echo yes # prints "yes" – glenn jackman Nov 11 '13 at 0:15
  • 1
    This accepted answer might also point out another difference being that with && the linked commands form a compound command which is jointly backgrounded subsequent & whereas the ; being two sequential commands will wait for completion of the first command before a trailing & will background the second command. sleep 5s && sleep 5s & echo "waited 0s" vs "sleep 5s; sleep 5s & echo "waited 5s" – humanityANDpeace Aug 4 '16 at 14:38
2

&& 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.

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