UNIX and Linux shell scripting "And" and "Or"

The "and" control flow is used to execute a command only if the previous command returns zero. "or" executes a command only if the previous command returns non-zero.

The general form of "And" is:

command1 && command2

command2 is executed only if command1 returns zero.

The general form of "Or" is:

command1 || command2

command2 is executed only if command1 returns non-zero.

"And" and "or" are great little shortcuts for simple "if" or "unless" control flows.

Example 1: Checking a file exists before deleting it

A classic little problem. You want to delete a file in a shell script but maybe that file doesn't exist in the first place. Of course, you don't want nasty errors by using an "rm" command on a non-existent file. Here we check if the file exists before trying to remove it.

test -f /tmp/myfile && rm /tmp/myfile

Example 2: Creating a directory only if it does not exist already

This example is similar to the last one. We want to create a directory, but not if it exists already, so we test first to see if that directory exists:

test -d /tmp/myDirectory || mkdir /tmp/myDirectory

A quick read of our page on test operators shows that you could replace "test" with square brackets. The statement above would now look like the following. It functions in exactly the same way, but it's slightly easier to read:

[ -d /tmp/myDirectory ] || mkdir /tmp/myDirectory