Command1 || command2

The second command is only started if the first command fails. The shell checks the exit status of the first command and starts the second command only if that exit status is not equal to 0:

    $ ls /root  ||  echo "Command execution failed"

Example:

    $ ls || echo "command ls failed"

In the preceding example, if ls runs successfully, then echo will not be called. If the ls command fails, such as $ ls /root, and if the user is not the root, then ls will fail and the echo command will print command ls failed.

When && or || are used, the exit status of the first command is checked first, and then the decision to perform the next will be taken.

For example:

    $ ls
    $ echo $?
      0
    $ ls /root
        ls: /root: Permission denied
    $ echo $? ...

Get Learning Linux Shell Scripting - Second Edition 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.