What's the difference between executing multiple commands with &&
and ;
?
Examples:
echo "Hi\!" && echo "How are you?"
and
echo "Hi\!"; echo "How are you?"
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityIn 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.
||
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
&&
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
&&
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.
;
at all, nor do any of the answers.;
the meaning of;
is implied, since it's the alternative.;
is implied. For people that are familiar with programming, sure. But for newcomers? Not so much.