What's the difference between executing multiple commands with &&
and ;
?
Examples:
echo "Hi\!" && echo "How are you?"
and
echo "Hi\!"; echo "How are you?"
What's the difference between executing multiple commands with &&
and ;
?
Examples:
echo "Hi\!" && echo "How are you?"
and
echo "Hi\!"; echo "How are you?"
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.
||
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 00: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"
– humanityANDpeace
Aug 04 '16 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. – phemmer Nov 11 '13 at 03:32;
the meaning of;
is implied, since it's the alternative. – slm Nov 11 '13 at 06:17;
is implied. For people that are familiar with programming, sure. But for newcomers? Not so much. – Zach Latta Nov 11 '13 at 07:01