Which one is better: using ; or && to execute multiple commands in one line?
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.
&&
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
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 &&
.