Logical Operators in Bash

In this tutorial, you will learn about logical operators in Bash. Logical operators allow you to perform conditional logic by combining multiple conditions. They are commonly used in if, elif, and while statements to make decisions in your Bash scripts.


Types of Logical Operators in Bash

Bash supports three main types of logical operators:

  • AND Operator (&& or -a): Evaluates to true if both conditions are true.
  • OR Operator (|| or -o): Evaluates to true if at least one condition is true.
  • NOT Operator (!): Reverses the result of a condition.

Using Logical Operators in Bash

Logical operators are often used in if statements to perform compound conditional checks. Let’s explore each operator with examples.

AND Operator (&&)

The AND operator returns true only if both conditions are true. In Bash, you can use && or -a to represent the AND operator.

Example: Check if a number is between 10 and 20:

example.sh

</>
Copy
#!/bin/bash
num=15

if [ $num -ge 10 ] && [ $num -le 20 ]; then
  echo "The number $num is between 10 and 20."
else
  echo "The number $num is not between 10 and 20."
fi