Logical OR

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search

← Logical ANDHomeLogical Not ! →

Logical OR (||) is boolean operator. It can execute commands or shell functions based on the exit status of another command.


command1 || command2


First_command || Second_command

command2 is executed if, and only if, command1 returns a non-zero exit status. In other words, run command1 successfully or run command2.


cat /etc/shadow 2>/dev/null || echo "Failed to open file"

The cat command will try to display /etc/shadow file and it (the cat command) sets the exit stats to non-zero value if it failed to open /etc/shadow file. Therefore, 'Failed to open file' will be displayed cat command failed to open the file.

Find username else display an error

grep "^vivek" /etc/passwd || echo "User vivek not found in /etc/passwd"

How Do I Combine Both Logical Operators?

Try it as follows:

cat /etc/shadow 2>/dev/null && echo "File successfully opened." || echo "Failed to open file."

Make sure only root can run this script:

test $(id -u) -eq 0  && echo "You are root" || echo "You are NOT root"


test $(id -u) -eq 0  && echo "Root user can run this script." || echo "Use sudo or su to become a root user."

External links

← Logical ANDHomeLogical Not ! →