In this chapter we shall look at some of the logical operators. Logical operators are used to give “true” or “false” value based on set of conditions. There are 2 types of operators:
9.1 AND Operator
9.2 OR Operator
9.1 AND operator:
This operator will return true if both of the conditions are true. “&&” is the symbol used to specify AND operator. Below is the truth table:
True && True = True
True && False = False
False && True = False
False && False = False
Example:
Suppose we want to allow a student to write the exam if his age is above 18 and below 25. Then the shell script will be as below:
#!/bin/bash age=44 if [ "$age" -gt 18 ] && [ "$age" -lt 25 ] then echo "Student can write the exam" else echo "Student cannot write the exam" fi
Output:
Student cannot write the exam
In the above if statement “&&” can be replaced by “-a” as shown below:
#!/bin/bash age=44 if [ "$age" -gt 18 -a "$age" -lt 25 ] then echo "Student can write the exam" else echo "Student cannot write the exam" fi
Output:
Student cannot write the exam
So if you want to use single bracket use “-a” operator. If you want to use double brackets use “&&” operator.
9.2 OR operator:
This operator will return true if any one of the conditions are true. If both of the conditions are false, then it will return false.
“||” is the symbol used to specify or operator. Below is the truth table:
True && True = True
True && False = True
False && True = True
False && False = False
Example:
Suppose we want to allow a student to write the exam if his age is above 18 or age is less than 25.
Then the shell script will be as below:
#!/bin/bash age=19 if [ "$age" -gt 18 ] || [ "$age" -lt 25 ] then echo "Student can write the exam" else echo "Student cannot write the exam" fi
Output:
Student can write the exam
As the first condition is true, then the output is true.
“-o” can be used instead of “||” to use single bracket.