Conditional Statements
Understanding Conditional Structures
Conditional statements are essential control structures in Linux shell scripting that enable decision-making and program flow control based on specific conditions.
Types of Conditional Statements
graph TD
A[Conditional Statements] --> B[if Statement]
A --> C[if-else Statement]
A --> D[if-elif-else Statement]
A --> E[Case Statement]
Basic if
Statement
The simplest form of conditional statement checks a single condition:
#!/bin/bash
x=10
if [ $x -gt 5 ]; then
echo "x is greater than 5"
fi
if-else
Statement
Provides an alternative execution path when the condition is not met:
#!/bin/bash
age=17
if [ $age -ge 18 ]; then
echo "You are an adult"
else
echo "You are a minor"
fi
if-elif-else
Statement
Handles multiple conditions sequentially:
#!/bin/bash
score=85
if [ $score -ge 90 ]; then
echo "Excellent"
elif [ $score -ge 80 ]; then
echo "Good"
elif [ $score -ge 60 ]; then
echo "Passing"
else
echo "Fail"
fi
case
Statement
Provides a multi-way branch for more complex condition checking:
#!/bin/bash
day="Monday"
case $day in
"Monday")
echo "Start of work week"
;;
"Friday")
echo "End of work week"
;;
*)
echo "Midweek day"
;;
esac
Conditional Operators
Operator |
Description |
Example |
-a |
Logical AND |
[ condition1 -a condition2 ] |
-o |
Logical OR |
[ condition1 -o condition2 ] |
! |
Logical NOT |
[ ! condition ] |
Nested Conditionals
You can nest conditional statements for more complex logic:
#!/bin/bash
x=10
y=20
if [ $x -lt $y ]; then
if [ $x -gt 5 ]; then
echo "x is between 5 and 20"
fi
fi
LabEx Tip
LabEx provides interactive environments to practice and master these conditional statement techniques.
Best Practices
- Use square brackets
[ ]
for conditions
- Always quote variables
- Use meaningful variable names
- Test scripts thoroughly
Common Mistakes
- Forgetting spaces around operators
- Incorrect comparison syntax
- Not handling all possible conditions
By understanding and practicing these conditional statements, you'll be able to write more dynamic and intelligent shell scripts in Linux.