[bash] What is the purpose of "&&" in a shell command?

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)

This question is related to bash shell command-line syntax

The answer is


See the example:

mkdir test && echo "Something" > test/file

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.


####################### && or (Logical AND) ######################
first_command="1"
two_command="2"

if [[ ($first_command == 1) && ($two_command == 2)]];then
 echo "Equal"
fi

When program checks if command, then the program creates a number called exit code, if both conditions are true, exit code is zero (0), otherwise, exit code is positive number. only when displaying Equal if exit code is produced zero (0) that means both conditions are true.


&& 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.


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.

$ false || echo "Oops, fail"
Oops, fail

$ true || echo "Will not be printed"
$  

$ true && echo "Things went well"
Things went well

$ false && echo "Will not be printed"
$

$ false ; echo "This will always run"
This will always run

Some details about this can be found here Lists of Commands in the Bash Manual.


command-line - what is the purpose of &&?

In shell, when you see

$ command one && command two

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.

You may notice I've used the word "intent" - that's for good reason. Not all programs have the same behavior, so for this to work, you need to understand what the program considers a "failure" and how it handles it by reading the documentation and, if necessary, the source code.

Your shell considers a return value of 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 as AND_IF in the posix shell grammar, which is part of an and_or list of commands, which also include the || which is an OR_IF with similar semantics.

Grammar symbols, quoted from the documentation:

%token  AND_IF    OR_IF    DSEMI
/*      '&&'      '||'     ';;'    */

And the Grammar (also quoted from the documentation), which shows that any number of AND_IFs (&&) and/or OR_IFs (||) can be be strung together (as and_or is defined recursively):

and_or           :                         pipeline
                 | and_or AND_IF linebreak pipeline
                 | and_or OR_IF  linebreak pipeline

Both operators have equal precedence and are evaluated left to right (they are left associative). As the docs say:

An AND-OR list is a sequence of one or more pipelines separated by the operators "&&" and "||" .

A list is a sequence of one or more AND-OR lists separated by the operators ';' and '&' and optionally terminated by ';', '&', or .

The operators "&&" and "||" shall have equal precedence and shall be evaluated with left associativity. For example, both of the following commands write solely bar to standard output:

$ false && echo foo || echo bar
$ true || echo foo && echo bar
  1. In the first case, the false is a command that exits with the status of 1

    $ false
    $ echo $?
    1
    

    which means echo foo does not run (i.e., shortcircuiting echo foo). Then the command echo bar is executed.

  2. In the second case, true exits with a code of 0

    $ true
    $ echo $?
    0
    

    and therefore echo foo is not executed, then echo bar is executed.


command_1 && command_2: execute command_2 only when command_1 is executed successfully.

command_1 || command_2: execute command_2 only when command_1 is not successful executed.

Feels similar as how an 'if' condition is executed in a mainstream programming language, like, in if (condition_1 && condition_2){...} condition_2 will be omitted if condition_1 is false and in if (condition_1 || condition_2){...} condition_2 will be omitted if condition_1 is true. See, it's the same trick you use for coding :)


It's to execute a second statement if the first statement ends succesfully. Like an if statement:

 if (1 == 1 && 2 == 2)
  echo "test;"

Its first tries if 1==1, if that is true it checks if 2==2


&& lets you do something based on whether the previous command completed successfully - that's why you tend to see it chained as do_something && do_something_else_that_depended_on_something.


A quite common usage for '&&' is compiling software with autotools. For example:

./configure --prefix=/usr && make && sudo make install

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...

tar xf package.tar.gz && ( cd package; ./configure && make && sudo make install ) && rm package -rf

I do this when for example making a linux from scratch box.


Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to command-line

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Flutter command not found Angular - ng: command not found how to run python files in windows command prompt? How to run .NET Core console app from the command line Copy Paste in Bash on Ubuntu on Windows How to find which version of TensorFlow is installed in my system? How to install JQ on Mac by command-line? Python not working in the command line of git bash Run function in script from command line (Node JS)

Examples related to syntax

What is the 'open' keyword in Swift? Check if returned value is not null and if so assign it, in one line, with one method call Inline for loop What does %>% function mean in R? R - " missing value where TRUE/FALSE needed " Printing variables in Python 3.4 How to replace multiple patterns at once with sed? What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? How can I fix MySQL error #1064? What do >> and << mean in Python?