In this tutorial, we aim to guide you through the correct usage of logical operators in shell scripting. By the end of this tutorial, you will have a clear understanding of how to combine conditional statements using logical operators to evaluate more complex conditions in your shell scripts.
Prerequisites:
Logical operators are special symbols that control the execution of conditional expressions and loops. In shell scripting, there are three types of logical operators: AND, OR, and NOT.
-a
or &&
.-o
or ||
.!
.Best practices:
- Always use spaces around operators to avoid syntax errors.
- Use brackets to clarify precedence when multiple operators are used together.
Example 1: AND Operator
age=25
if [ $age -gt 18 ] && [ $age -lt 30 ]
then
echo "Valid age"
else
echo "Invalid age"
fi
This script checks if the variable age
is greater than 18 AND less than 30. If both conditions are true, it prints "Valid age"; otherwise, "Invalid age".
Example 2: OR Operator
is_day=true
is_sunny=false
if [ $is_day = true ] || [ $is_sunny = true ]
then
echo "Go outside"
else
echo "Stay indoors"
fi
This script checks if it is day OR if it is sunny. If either condition is true, it advises to "Go outside"; otherwise, "Stay indoors".
In this tutorial, we've covered how to use AND, OR, and NOT logical operators in shell scripting. Next, you can learn about arithmetic operators and how to use them in shell scripts. Visit Shell Scripting Tutorial for further learning.
Solutions:
num=10
if [ $num -gt 0 ] || [ $(($num % 2)) -eq 0 ]
then
echo "Number is positive or even"
else
echo "Number is not positive or even"
fi
age=20
if [ $age -ge 18 ]
then
echo "Person is eligible to vote and drive"
else
echo "Person is not eligible to vote or drive"
fi
Keep practicing with different conditions and operators to get a good grip on logical operators!