Conditional Expressions
Understanding Conditional Logic
Conditional expressions form the core of decision-making in shell scripting, allowing scripts to perform different actions based on specific conditions.
Logical Operators
Logical AND and OR
graph TD
A[Logical Operators] --> B[AND: -a or &&]
A --> C[OR: -o or ||]
A --> D[NOT: !]
Operator Comparison
Operator |
Meaning |
Example |
-a |
Logical AND |
[ condition1 -a condition2 ] |
-o |
Logical OR |
[ condition1 -o condition2 ] |
! |
Logical NOT |
[ ! condition ] |
Complex Conditional Expressions
Nested Conditions
#!/bin/bash
## Complex condition example
if [ $age -ge 18 ] && [ $age -le 65 ]; then
echo "You are in the working age group"
fi
## Alternative syntax
if [[ $age -ge 18 && $age -le 65 ]]; then
echo "You are in the working age group"
fi
Advanced Conditional Techniques
Multiple Condition Checking
#!/bin/bash
## Multiple condition check
check_system() {
if [[ -f /etc/os-release ]] \
&& [[ $(cat /etc/os-release | grep -i ubuntu) ]] \
&& [[ $(whoami) == "root" ]]; then
echo "Ubuntu system with root access"
else
echo "System requirements not met"
fi
}
check_system
Conditional Expression Patterns
graph TD
A[Conditional Patterns] --> B[Numeric Comparisons]
A --> C[String Comparisons]
A --> D[File Conditions]
B --> B1[Equal, Not Equal]
B --> B2[Greater, Less]
C --> C1[Matching]
C --> C2[Length]
D --> D1[Existence]
D --> D2[Permissions]
Common Pitfalls
- Always quote variables to prevent word splitting
- Use
[[
for more robust condition checking in Bash
- Be aware of whitespace in conditions
Practical Use Cases
#!/bin/bash
## User input validation
read -p "Enter your age: " age
if [[ $age =~ ^[0-9]+$ ]]; then
if [ $age -lt 18 ]; then
echo "You are a minor"
elif [ $age -ge 18 ] && [ $age -le 65 ]; then
echo "You are an adult"
else
echo "You are a senior citizen"
fi
else
echo "Invalid age input"
fi
LabEx Insight
LabEx recommends practicing conditional expressions through interactive shell scripting environments to build practical skills.