Bash Pipelines and Compound Commands

What does && mean? Or maybe ||? Or what about ;?

Compound Commands

Compound commands are a way to run multiple commands in one fell swoop. For example:


echo "Hello" && echo "world"

What the above command does is to echo the word ‘Hello’ to screen and then echo the word ‘world’ to screen.

So why is this useful? Well it is, especially when you have commands that take a long time to run, but need to be run consecutively. A common example of this is:


make && sudo make install

This is used to first compile a program from source, and then install it.

OK, let’s run through the different options next.

The AND operator: &&

&& is the Bash AND operator:


command1 && command2

The AND operator means that command2 is only executed if command1 executes without error (in advanced terms, an exit status of zero). This means that if command1 comes up with an error (for example, if ‘make’ fails) command2 will not be executed.

The OR operator: ||

|| is the Bash OR operator:


command1 || command2

The OR operator means that command2 will be executed only if command1 FAILS. This can be useful if you need to change the flow of a script when something goes wrong. To continue with the theme of compiling programs:


make || echo "The make failed"

As you can see, the OR operator can be used to return a message if the make fails…

Sequential operator: ;

Executing a list of commands with ; means that all the commands in the list are executed regardless of the exit statuses.


command1 ; command2

command2 will be executed regardless of whether command1 was executed successfully. This is useful when it doesn’t matter command2 doesn’t depend on the outcome of command1.

Background execution: &

If a command is suffixed with & the command will be executed in the background. That means that the next command will be executed without waiting for the previous command the be completed.


command1 & command2

command1 will be executed “asynchronously in a subshell.”

This can also be used to launch GUI programs when you want regain use of the terminal window once the program has been launched, for example:


gedit&

Pipelines

The Pipe: |


command1 | command2

| is used to pipe the output of command1 to command2. A common use for this is when you use the ‘less’ command to show a screenful of text at a time. For example:


cat /var/log/kernel.log | less

Further Reading