28. Bash Shell - Most Commonly Used Control Operators
Contents
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:
|
|

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:
|
|
Usage of &&
We can print the contents of the two files in order:
|
|

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:
|
|

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:
|
|
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:
|
|

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:
|
|

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:
|
|

Prints the contents of the second file only
References Bash Reference Manual - Page 9 - 3.2.3 Lists of Commands
Author Dong Chen
LastMod Fri Mar 1 2019