Linux Command Line Logical Operators AND (&&) OR (||) usage
In this article, you are going to learn how to use logical operators in the Linux command line.
Logical operators are fundamental tools that allow us to make decisions in our scripts and commands based on the outcomes of previously executed code.
There are two types of logical operators available in Linux: the AND operator and the OR operator.
These operators help us implement logical conditions in our command sequences, enhancing the functionality and efficiency of our scripts.
Types of Logical Operators:
AND Operator (&&)
The AND operator (&&) in Linux is used to execute commands conditionally. It works based on the exit status of the preceding command.
In Linux, an exit status of 0 typically signifies success, while any non-zero exit status indicates some form of error or failure.
Syntax: command1 && command2
Usage: command2 is executed if and only if command1 succeeds (returns a zero exit status).
Example: $ mkdir new_directory && cd new_directory
Here, cd new_directory is executed only if mkdir new_directory is successful.
OR Operator (||)
The OR operator (||) in Linux is used for conditional execution of commands. It operates based on the exit status of the preceding command.
In Linux, if a command exits with a status of 0, it is deemed successful, and thus, the command following the OR operator is not executed.
Conversely, a non-zero exit status, which indicates an error or some form of failure, triggers the execution of the command following the OR operator.
Example with One Operator (&& or ||):
Example with Two Operators (&& or ||):
Example with Three Operators (Two && and One ||):