We can use the control operators provided by linux to facilitate the use of commands and the processing of the results of command execution.

Let’s prepare some test data for these two control operators:

1
2
3
4
printf '%s\n' 'File One First Line' 'File One Second Line' > file1
printf '%s\n' 'File Two First Line' 'File Two Second Line' > file2
cat file1
cat file2
img

Prints multiple lines of test data to two files

Ampersand Ampersand Operator

We can use two ampersand symbol to concatenate a series of commands and execute them sequentially:

1
&&

Usage of &&

We can print the contents of the two files in order:

1
cat file1 && cat file2
img

Print the contents of each file sequentially

When a Command in Ampersands Fails

When a command fails, none of its subsequent commands will be executed.

Let’s try printing a file that doesn’t exist:

1
cat file11 && cat file2
img

Prints an error message, because the first file does not exist

Pipe Pipe Operator

Another control works differently, executing the next command only if the previous command fails:

1
||

Usage of ||

We can print the contents of one of the files, and when the previous file does not exist, then the contents of the following file is printed:

1
cat file1 || cat file2
img

Print the first file's content only

When a Command in Pipes Fails

When a command fails, the next command will be executed.

Let’s try printing a file that doesn’t exist:

1
cat file11 || cat file2
img

Prints an error from the first command and followed by the contents of the second file

Ignore the Error Message

We can redirect the error message to null:

1
cat file11 2> /dev/null || cat file2
img

Prints the contents of the second file only

References Bash Reference Manual - Page 9 - 3.2.3 Lists of Commands

Buy me a coffeeBuy me a coffee