Understanding Linux sequences

Linux has some powerful sequence controls that you can use to run processes in different orders, sequentially, in parallel or conditionally.

Sequence: “;”

this will throw an error; echo "but this will still run"

Commands seperated by a ; are run sequentially. The shell waits for each command to terminate before returning. As seen in the gif it doesn’t matter if either command fails or not.

;-gif

Sequence: “&&”

echo "this will run first" && echo "and then this will run"
this won't run & echo "so this wont run b/c the first command threw an error"

Commands seperated by a && are run one after another and the second command is only run if the first one returns an exit code of zero aka runs successfully.

&&-gif

Sequence: “&”

echo "runs in the background" &

A command with a & at the end of it runs in the background and does not wait for the command to finish and returns immediately successfully with an exit code of 0. It returns with an exit code of 0 even if the command itself fails.

amp-gif

Sequence: “|”

echo "passing this to the next command" | cat

The standard output of command1 is sent to the standard input of command2. So in this example we’re using cat to output the standard input which is the echo’ed statement.

piepe-gif

Sequence: “||”

this will fail || echo "but this will run bc the first command failed"

The command after the || is executed only if the command before the || returns a non-zero status aka it errors. It is akin to an OR operator.

double-pipe-gif

Sequence: “|&”

echo "similar to | but also shows the error" |& cat

Is shorthand for 2>&1 | which means the standard output and standard error of the command are sent to via the pipe to the following command.

amp-gif

Read more about here

Instagram Post