Logical Operators are also known as boolean operators. These are used to perform logical operations. It will return two values that is either the output will be true or false. We can make decision regarding an process to proceed. Logical operations are of 3 types.
Logical AND ( && ) or ( -a ) :
An AND logical operator will be true when both the operands are true. If either one of the operand is false then it will return false.
AND operator can be used in a sh script when we will be using multiple commands in a single line.
Using a truth table we can have a clear idea for an AND logical operator.
if (( $val1 == "true" -a $val2 == "true" ))
then
The output is true.
else
The output is false.
fi
Run the file,
jhony@ljlinux:~$ ./and.sh
Enter val1 : true
Enter val2 : true
The output is true.
Explanation of the code:
Step 1: Getting the inputs from the users as val1 and val2. Since it is logical operation either the inputs should true or false. Step 2: With -a operator we are performing AND logical operation. Step 3: Using if statement will print the output.
Logical OR ( || ) or ( -o ) :
A logical OR operator returns true if any of the operands is true. It will return false if both the operands is false.
An OR logical operators truth table is given below.
if (( $val1 == "true" -o $val2 == "true" ))
then
The output is true.
else
The output is false.
fi
Run the file,
jhony@ljlinux:~$ ./or.sh
Enter val1 : true
Enter val2 : false
The output is true.
Explanation of the code:
Step 1: Getting the inputs from the users as val1 and val2. Since it is logical operation either the inputs should true or false. Step 2: With -o operator we are performing OR logical operation. Step 3: Using if statement will print the output.
NOT logical Operator ( -n ) or ( ! ) :
It is a uninary operator which returns true if the operand is false and returns false if the operand is true.
Open a file as notequal.sh
Truth table for a NOT logical operator.
Logical NOT
Input
Output
TRUE
FALSE
FALSE
TRUE
$ vim not.sh
Paste the below code
Code:
#!/bin/sh
echo "Enter the input:"
read val
if (( $val -n "true" ))
then
echo The output is false.
else
echo The output is true.
fi
Run the file,
jhony@ljlinux:~$ ./not.sh
Enter the input:
false
The output is true.
Explanation of the code: Step 1: Getting the input from the user as val. Step 2: With -n operator we are comparing the given values. Step 3: Using if statement will print the ouput as true if its false and vice versa.
Note:
We can either use the operator with alphabetic expression or direct operators( && or -a ) and ( || or -o ).
That's it for Logical operators. Feel free to ask if you have any queries.
Comments