Logical Operators in Shell Scripting

In shell scripting, logical operators are used to perform operations on Boolean values (true or false) or on the exit status of commands. These operators allow you to make decisions based on conditions.

Here are the three main logical operators in shell scripting:

1. AND Operator (&&):

  • Syntax: command1 && command2
  • Description: The && operator executes command2 only if command1 is successful (returns a zero exit status).

Example:

Bash
bash command1 && command2

Usage: (This will only echo “Command succeeded.” if the touch command succeeds.)

Bash
touch myfile.txt && echo "Command succeeded."

2. OR Operator (||):

  • Syntax: command1 || command2
  • Description: The || operator executes command2 only if command1 fails (returns a non-zero exit status).

Example:

Bash
bash command1 || command2

3. NOT Operator (!):

  • Syntax: ! command
  • Description: The ! operator negates the exit status of the command. If the command succeeds (returns a zero exit status), ! makes it fail, and vice versa.

Example:

Bash
! condition # A condition to be checked. 

Usage:

Bash
# This will only echo "Condition is false." if the condition is not true.
if ! true; then
    echo "Condition is false."
fi

In the first example, the && operator is used to execute the second command only if the first command succeeds. If the file doesn’t exist, the second command will not be executed.

In the second example, the || operator is used to execute the second command only if the first command fails. If the file doesn’t exist, the second command will be executed.

In the third example, the ! operator is used to negate the exit status of the command. If the command fails, the ! makes it succeed, and vice versa.

Logical operators are particularly useful in control structures like if-else statements and loops, allowing you to make decisions based on the success or failure of commands. They also play a crucial role in error handling and conditional execution of tasks in shell scripts.

Share
OpenLib .

OpenLib .

The Founder - OpenLib.io

You may also like...