Which one is better: using ; or && to execute multiple commands in one line?
In tutorials and how-to's I often see commands combined. For instance,
sudo apt-get update && sudo apt-get install pyrenamer
There seem to be four possible connectors: &
, &&
, ||
and ;
. Though the &
connector is clear to me (it sends a process to the background and leaves the terminal available), it is not clear what the difference is between &&
and ;
. And I did not know of ||
until Kaya's comment.
The following questions deal with the difference between the two connectors, but do so mostly in the comments:
How to start two Ubuntu applications in one go?
How to combine multiple commands in terminal?
So here are a number of related questions:
- What is the difference between
;
and&&
? - When should you use them respectively? It would be nice to see some use cases: if I want to run a command and then after it shutdown my computer, which connector should I choose?
- What are their advantages and dangers? Robie Basak mentions in a comment to this answer that a command like
cd /somewhere_else; rm -Rf *
can have destructive consequences if the first element in the command chain fails, for instance. - If relevant, where do they come from?
Solution 1:
Cheatsheet:
A; B # Run A and then B, regardless of success of A
A && B # Run B if and only if A succeeded
A || B # Run B if and only if A failed
A & # Run A in background.
Solution 2:
&&
only runs the second command if the first one exited with status 0 (was successful). ;
runs both the commands, even if the first one exits with a non zero status.
Your example with &&
can be equivalently paraphrased as
if sudo apt-get update ; then
sudo apt-get install pyrenamer
fi
Solution 3:
Using ;
will execute the commands irrespective whether first command is successful or not.
Using &&
will execute the second command only when first command executed successfully (status 0).
Both are used on different perspective. Like for a longer process, say for an installation you need to compile and install it. you should make && make install
. So the install will run only if make
successful.
So for dependent commands you should use &&
.
Wring bash, or commands with independent commands, use ;
.
So if you want to shutdown computer even the first job failed use ;
, but if want on complete success of first job initiate the shutdown use &&
.
Solution 4:
a ; b
will run b regardless of the exit status of a. a && b
will run b only if a succeeded.
This is necessary and sufficient to answer to the first 3 questions. In particular, the 2 is too broad, and cannot be given "one" definitive answer - your best bet is to decide on a case by case basis.
As for the 4th question: They're Bash syntax.
There is no intrinsic danger in using either. Again, the definition above is sufficient. It implies that you will write &&
when b
has unintended effects if a
does not succeed. There is no need for further rules or explanation, IMHO.