Bash command chaining operators

Semicolon operator (;)

The semicolon operator executes the commands sequentially.

$ command1; command2

The above instruction will first execute command1. On both success or failure of command1, it will go ahead and execute command2.

Ampersand operator (&)

The ampersand operator positionned after a command, executes it in the background. When chaining commands, where each command is followed by the & operator, all commands will be executed in background, simultaneously.

$ command1 & command2 &

The above instruction will execute command1 and command2 in background, simultaneously.

AND operator (&&)

The AND(double ampersand) operator executes the command after the operator only if the one before succeeds.

$ command1 && command2

The above instruction will execute command2 only if command1 succeeds.

OR operator (||)

The OR(double pipe) operator acts as a else statement. It executes the command after the operator only if the one before fails.

$ command1 || command2

The above instruction will execute command2 only if command1 fails.

PIPE operator (|)

The PIPE operator lets the previous command standard output to be passed as the standard input of the following command. This often comes in handy when you want to filter the output of the previous command.

$ history | grep npm

The above instruction will execute the history command, and filter its output to only display lines including the string npm.

AND – OR operator (&& – ||)

The AND – OR operator is nothing else than the combination of AND and OR operators. It acts as a if – else statement.

$ command1 && upon-command1-success || upon-command1-failure

The above instruction will execute command1 first. If it succeed, it will execute upon-command1-success. If command1 fails, it will execute upon-command1-failure