6.2. Using ||

The general format of the || is:

command1 || command2 

The operation of the || is slightly different. If the command on the left of the || (command1) fails then execute the command on the right of the || (command2); or to put it another way, ‘If this command fails’ || ‘then execute this command’.

Here’s another simple example that illustrates the use of the ||:

						$ cp wopper.txt oops.txt || echo "if you are seeing this cp failed" 

cp: wopper.txt: No such file or directory 
if you are seeing this cp failed
					

The copy has failed so now the command on the right-hand side of the || is executed.

A more practical example is this. I want to extract the first and fifth fields from an accounts file and stick the output into a temp file. If ...

Get Linux and Unix Shell Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.