As far as I know, using &
after the command is for running it in the background.
Example of &
usage: tar -czf file.tar.gz dirname &
But how about &&
? (look at this example: https://serverfault.com/questions/215179/centos-100-disk-full-how-to-remove-log-files-history-etc#answer-215188)
&&
lets you do something based on whether the previous command completed successfully - that's why you tend to see it chained asdo_something && do_something_else_that_depended_on_something
.In shell, when you see
the intent is to execute the command that follows the
&&
only if the first command is successful. This is idiomatic of Posix shells, and not only found in Bash.It intends to prevent the running of the second process if the first fails.
Processes return 0 for true, other positive numbers for false
Programs return a signal on exiting. They should return 0 if they exit successfully, or greater than zero if they do not. This allows a limited amount of communication between processes.
The
&&
is referred to asAND_IF
in the posix shell grammar, which is part of anand_or
list of commands, which also include the||
which is anOR_IF
with similar semantics.Grammar symbols:
Grammar:
Both operators have equal precedence and are evaluated left to right (they are left associative) For example, the following:
both echo only
bar
.In the first case, the false is a command that exits with the status of
1
which means
echo foo
does not run (i.e., shortcircuitingecho foo
). Then the commandecho bar
is executed.In the second case, true exits with a code of
0
and therefore
echo foo
is not executed, thenecho bar
is executed.Furthermore, you also have
||
which is the logical or, and also;
which is just a separator which doesn't care what happend to the command before.Some details about this can be found here Lists of Commands in the Bash Manual.
A quite common usage for '&&' is compiling software with autotools. For example:
Basically if the configure succeeds, make is run to compile, and if that succeeds, make is run as root to install the program. I use this when I am mostly sure that things will work, and it allows me to do other important things like look at stackoverflow an not 'monitor' the progress.
Sometimes I get really carried away...
I do this when for example making a linux from scratch box.
See the example:
Shell will try to create directory
test
and then, only if it was successfull will try create file inside it.So you may interrupt a sequence of steps if one of them failed.
&&
strings commands together. Successive commands only execute if preceding ones succeed.Similarly,
||
will allow the successive command to execute if the preceding fails.See Bash Shell Programming.