首页 > 代码库 > bash - Logical_OR

bash - Logical_OR

转载

https://bash.cyberciti.biz/guide/Logical_OR

 

Logical OR

 

 
← Logical AND Home Logical Not ! →

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

Contents

  • 1 Syntax
    • 1.1 Example
      • 1.1.1 Find username else display an error
    • 1.2 How Do I Combine Both Logical Operators?
  • 2 External links

Syntax

command1 || command2

OR

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.

Example

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"

OR

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

External links

  • How to display error message instantly when command fails
← Logical AND

bash - Logical_OR