What is the difference between & (ampersand) and && (double ampersand) while executing simultaneous commands on Linux

To run more that one command simultaneously we can use the & (ampersand) special character. Another use of & is running the commands in the background. In that case though, you should use & once and the end of the command or script. For example:

# [some command or script] &

Using & (ampersand) to run commands simultaneously

In order to run 2 commands simultaneously use the & special character between the 2 or more commands. The syntax is:

# command1 & command2 & command3 ..

For example, if you want to run 3 commands ‘uname -a’, ‘pwd’ and ‘ls’ simultaneously, you can use:

# hostname & pwd & date

The output would be similar to:

# hostname & pwd & date
[1] 3253
[2] 3254
/root
geeklab
Sat Jan 18 05:46:07 UTC 2020
[1]-  Done                    hostname
[2]+  Done                    pwd

When using single &, even when a command fails the next commands is run.

Using && (double ampersand) to run commands simultaneously

In case if you want that the second job/command needs to wait for the first job/command to finish, use the && between the commands. So in that way if any error occurs while the sentence is being executed it will stop. For example:

# hostname && pwd && date

Sample output:

$ hostname && pwd && date
geeklab01
/root
Sat Jan 18 12:23:34 IST 2020

Lets try using a wrong command and see if the next commands are executed:

$ hostname && wrngcmd && date
geeklab01
-bash: wrngcmd: command not found

As shown above the last command “date” was not executed as the command before it was wrong.

Related Post