Logical Operators
Introduction to Logical Operators
Logical operators are essential for combining multiple conditions in shell scripts, allowing complex decision-making and conditional logic. In Bash, there are three primary logical operators: AND, OR, and NOT.
Logical Operators Overview
Operator |
Symbol |
Description |
Syntax |
AND |
-a or && |
Both conditions must be true |
[ condition1 -a condition2 ] |
OR |
-o or || |
At least one condition must be true |
[ condition1 -o condition2 ] |
NOT |
! |
Negates the condition |
[ ! condition ] |
AND Operator Examples
Traditional AND Operator (-a)
#!/bin/bash
age=25
name="John"
if [ $age -gt 18 -a "$name" = "John" ]; then
echo "Condition satisfied: Adult named John"
fi
Modern AND Operator (&&)
#!/bin/bash
[ $age -gt 18 ] && [ "$name" = "John" ] && echo "Condition satisfied"
OR Operator Examples
Traditional OR Operator (-o)
#!/bin/bash
status=1
user="admin"
if [ $status -eq 0 -o "$user" = "admin" ]; then
echo "Access granted"
fi
Modern OR Operator (||)
#!/bin/bash
[ $status -eq 0 ] || [ "$user" = "admin" ] || echo "Access denied"
NOT Operator Example
#!/bin/bash
file="/etc/passwd"
if [ ! -f "$file" ]; then
echo "File does not exist"
fi
Logical Operators Flow
graph TD
A[Start] --> B{First Condition}
B -->|True| C{Second Condition}
B -->|False| D{Logical Operator}
D -->|AND| E[Entire Condition False]
D -->|OR| F[Check Next Condition]
C -->|True| G[Condition Satisfied]
C -->|False| H[Condition Not Satisfied]
Combining Multiple Conditions
#!/bin/bash
age=25
is_student=true
has_discount=false
if [ $age -lt 30 -a "$is_student" = true -a "$has_discount" = false ]; then
echo "Eligible for special offer"
fi
Best Practices
- Use
&&
and ||
for more readable code
- Always quote variables to prevent unexpected behavior
- Test complex conditions carefully
- Use parentheses for complex logical expressions
LabEx recommends practicing these logical operators to enhance your shell scripting skills and create more sophisticated conditional logic.