45

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

Examples:

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

and

echo "Hi\!"; echo "How are you?"
3
  • 5
    Don't agree on the duplicate. That question doesn't even mention ; at all, nor do any of the answers.
    – phemmer
    Nov 11, 2013 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, 2013 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, 2013 at 7:01

2 Answers 2

60

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.

2
  • 8
    || is the opposite of &&: the RHS is executed if the LHS does not succeed: false || echo yes # prints "yes" Nov 11, 2013 at 0:15
  • 3
    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" Aug 4, 2016 at 14:38
4

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