Shell Programming - Logical Operators

Unix

In this tutorial we will learn about Logical Operators in Shell Programming.

We use the logical operators to test more than one condition.

Following are the logical operators that we will be discussing.

OperatorDescription
-aLogical AND
-oLogical OR

Click here to learn about Boolean Algebra.

In this tutorial we will be using if statement.

Logical AND

The logical AND -a operator will give true if both the operands are true. Otherwise, false.

Truth table of logical AND operator.

ABA -a B
falsefalsefalse
falsetruefalse
truefalsefalse
truetruetrue

In the following example we will check if the number is even and greater than 10.

To check if a number is even we use the Modulus Operator %. So, if a number is divisible by 2 and gives 0 as remainder then it is an even number otherwise, it is odd.

#!/bin/sh

# take a number from the user
echo "Enter a number: "
read a

# check
if [ `expr $a % 2` == 0 -a $a -gt 10 ]
then
  echo "$a is even and greater than 10."
else
  echo "$a failed the test."
fi

Output:

$ sh and.sh 
Enter a number: 
10
10 failed the test.

$ sh and.sh 
Enter a number: 
20
20 is even and greater than 10.

Logical OR

The logical OR -o operator will give true if any one of the operand is true. If both operands are false then it will return false.

Truth table of logical OR operator.

ABA -o B
falsefalsefalse
falsetruetrue
truefalsetrue
truetruetrue

In the following example we will check if entered number is either odd or less than 10.

#!/bin/sh

# take a number from the user
echo "Enter a number: "
read a

# check
if [ `expr $a % 2` != 0 -o $a -lt 10 ]
then
  echo "$a is either odd or less than 10."
else
  echo "$a failed the test."
fi

Output:

$ sh or.sh 
Enter a number: 
10
10 failed the test.

$ sh or.sh 
Enter a number: 
9
9 is either odd or less than 10.