Bash/sh - difference between && and ;
Solution 1
If previous command failed with ;
the second one will run.
But with &&
the second one will not run.
This is a "lazy" logical "AND" operand between operations.
Solution 2
I'm using &&
because a long time ago at the nearby computer:
root# pwd
/
root# cd /tnp/test; rm -rf *
cd: /tnp/test: No such file or directory
...
... and after a while ...
...
^C
but not helped... ;)
cd /tnp/test && rm -rf *
is safe... ;)
Solution 3
In cmd1 && cmd2
, cmd2
is only executed if cmd1
succeeds (returns 0).
In cmd1 ; cmd2
, cmd2
is executed in any case.
Both constructs are part of a POSIX-compliant shell.
Solution 4
&&
means to execute next command if the previous exited with status 0.
For the opposite, use ||
i.e. to be executed if previous command exits with a status not equal to 0 ;
executes always.
Very useful when you need to take a particular action depending on if the previous command finished OK or not.
Solution 5
Commands separate by ;
are executed sequentially regardless of their completion status.
With &&
, the second command is executed only if the first completes successfully (returns exit status of 0).
This is covered in the bash manpage under Lists
. I would expect any Unix-like shell to support both of these operators, but I don't know specifically about the Android shell.
Related videos on Youtube
Comments
-
psihodelia about 4 years
I normally use
;
to combine more than one command in a line, but some people prefer&&
. Is there any difference? For example,cd ~; cd -
andcd ~ && cd -
seems to make the same thing. What version is more portable, e.g. will be supported by a bash-subset like Android's shell or so? -
glenn jackman about 13 yearsHere's a link to the bash manual: gnu.org/software/bash/manual/bashref.html#Lists
-
melvynkim about 10 yearsTo be safer, I'd use
rm -rf /tnp/test
-
radrow almost 6 yearsTo be even safer it is better to use
rm /tnp/test/ -rf
to prevent deadly enter missclick -
Peter Chaula almost 6 yearsIn other words it's got a short-circuit behaviour
-
Shayan almost 5 years@peter Which one? The
;
one or the&&
one? Or do you mean both? -
Peter Chaula almost 5 years@Shayan, the
&&
. -
Vthechamp over 3 yearsSo you would prefer to run
sudo apt update && sudo apt upgrade
and notsudo apt update; sudo apt upgrade
, right? -
Scott H over 2 yearsNote that if you combine
&&
and||
, then you must put the&&
first. Otherwise, the&&
executes if either the original or the||
command succeeds (exits with 0 status).