Run another command when previous command completes
&&
means to run it if the previous command was successful. In Unix that generally means exit status 0.
$ ls barfoofba && echo "This will not be echo'd"
ls: cannot access 'barfoofba': No such file or directory
$ ls bar && echo "This will be echo'd"
This will be echo'd
In the first instance, ls
did not succeed, so it exited with a non-zero exit status, and bash did not run the second command.
In the second example, I ls'd a existing file, so ls exited with 0 as exit status, and the command was executed.
If you want to run commands unconditionally, e.g. not dependent on the result of the first, you may separate them with ;
like this
command1; command2; command3
and so forth.
Thus you may do
ls -lR ; sleep 4 ; gnome-terminal
In addition to &&
and ;
you have ||
which is the opposite of &&
: Only run the command if the previous command failed with a non-zero exit status. If the first command succeeds, the next will not be executed. If it fails, the next will be executed.
So in short:
&&
: Run if preceding command exited with 0;
: Run unconditionally||
: Run if preceding command exited with a non-zero exit status.&
: Run both commands in paralell, the first in background and second in foreground.
The command ls -lR
exited with an exit-status different than zero, so the following commands have not been executed. Most probably ls
was unable to open a subdirectory. It didn't happen in your first command because you didn't use the -R
-option.
From man bash
:
command1 && command2 command2 is executed if, and only if, command1 returns an exit status of zero.
From man ls
:
Exit status: 0 if OK, 1 if minor problems (e.g., cannot access subdirectory) 2 if serious trouble (e.g., cannot access command-line argument).