Comparison and Logic
Logical Operators Overview
Shell scripting provides powerful logical operators to combine and evaluate multiple conditions effectively.
Logical AND and OR Operators
Logical AND (&&
)
Executes the next command only if the previous command succeeds:
[ condition ] && command_if_true
Logical OR (||
)
Executes the next command if the previous command fails:
[ condition ] || command_if_false
Complex Condition Evaluation
Combining Multiple Conditions
#!/bin/bash
age=25
name="John"
if [ $age -ge 18 ] && [ "$name" == "John" ]; then
echo "Adult named John"
fi
Logical Operator Truth Table
Condition 1 |
Operator |
Condition 2 |
Result |
True |
&& |
True |
True |
True |
&& |
False |
False |
False |
&& |
True |
False |
False |
&& |
False |
False |
True |
|| |
True |
True |
True |
|| |
False |
True |
False |
|| |
True |
True |
False |
|| |
False |
False |
Nested Condition Flow
graph TD
A[Start] --> B{First Condition}
B -->|True| C{Second Condition}
B -->|False| G[Exit]
C -->|True| D[Execute Action]
C -->|False| G
Advanced Condition Checking
Negation Operator (!
)
Inverts the result of a condition:
if [ ! -f /path/to/file ]; then
echo "File does not exist"
fi
Comparison Types
- Numeric Comparisons
- String Comparisons
- File Test Conditions
Numeric Comparison Example
#!/bin/bash
x=10
y=20
if [ $x -lt $y ]; then
echo "x is less than y"
fi
String Comparison Example
#!/bin/bash
input="Hello"
if [ "$input" == "Hello" ]; then
echo "Greeting matches"
fi
LabEx Practical Tip
Experiment with these logical operators in LabEx's shell environment to master conditional logic techniques.