Bash Conditional Basics
Introduction to Conditional Statements
Conditional statements are fundamental to programming in Bash, allowing scripts to make decisions and control program flow based on specific conditions. In Linux shell scripting, these statements help create dynamic and intelligent scripts that can respond to different scenarios.
Basic Conditional Structure
In Bash, conditional statements primarily use the if-then-else
syntax. The basic structure looks like this:
if [ condition ]; then
## Commands to execute if condition is true
else
## Commands to execute if condition is false
fi
Types of Conditional Checks
Bash provides multiple ways to perform conditional checks:
1. File-based Conditions
## Check if file exists
if [ -f /path/to/file ]; then
echo "File exists"
fi
## Check if directory exists
if [ -d /path/to/directory ]; then
echo "Directory exists"
fi
2. String Comparisons
name="LabEx"
if [ "$name" == "LabEx" ]; then
echo "Name matches"
fi
## Check for empty string
if [ -z "$variable" ]; then
echo "Variable is empty"
fi
3. Numeric Comparisons
age=25
if [ $age -gt 18 ]; then
echo "Adult"
else
echo "Minor"
fi
Conditional Operators
Operator |
Description |
Example |
-eq |
Equal to (numeric) |
[ 5 -eq 5 ] |
-ne |
Not equal to (numeric) |
[ 5 -ne 6 ] |
-gt |
Greater than |
[ 10 -gt 5 ] |
-lt |
Less than |
[ 5 -lt 10 ] |
== |
Equal to (string) |
[ "$a" == "$b" ] |
!= |
Not equal to (string) |
[ "$a" != "$b" ] |
Logical Operators
## AND operator
if [ condition1 ] && [ condition2 ]; then
echo "Both conditions are true"
fi
## OR operator
if [ condition1 ] || [ condition2 ]; then
echo "At least one condition is true"
fi
Flow Visualization
graph TD
A[Start] --> B{Condition Check}
B -->|True| C[Execute True Block]
B -->|False| D[Execute False Block]
C --> E[Continue]
D --> E
Best Practices
- Always quote variables to prevent word splitting
- Use
[[ ]]
for more advanced conditional testing
- Keep conditions simple and readable
- Test scripts thoroughly in environments like LabEx