Conditional Fundamentals
Introduction to Bash Conditionals
In Bash scripting, conditional statements are crucial for creating dynamic and intelligent scripts. They allow you to make decisions and control the flow of your program based on specific conditions.
Basic Conditional Syntax
Bash provides several ways to perform conditional checks:
Test Command (test
or [ ]
)
The most common method for conditional checks is using the test
command or its shorthand [ ]
:
## Using test command
test condition
## Using square brackets
[ condition ]
Example of Simple Conditional Check
#!/bin/bash
## Check if a file exists
if [ -f /path/to/file ]; then
echo "File exists"
else
echo "File does not exist"
fi
Types of Conditions
File Conditions
Operator |
Description |
-f |
Checks if file exists and is a regular file |
-d |
Checks if directory exists |
-r |
Checks if file is readable |
-w |
Checks if file is writable |
-x |
Checks if file is executable |
String Conditions
## Check string equality
if [ "$string1" = "$string2" ]; then
echo "Strings are equal"
fi
## Check if string is empty
if [ -z "$string" ]; then
echo "String is empty"
fi
Numeric Conditions
## Compare numbers
if [ $num1 -eq $num2 ]; then
echo "Numbers are equal"
fi
## Other numeric comparisons
## -gt (greater than)
## -lt (less than)
## -ge (greater or equal)
## -le (less or equal)
## -ne (not equal)
Logical Operators
Combining Conditions
## 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
Conditional 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 conditionals in Bash
- Test your conditions thoroughly
LabEx Tip
When learning Bash conditionals, practice is key. LabEx provides an excellent environment for experimenting with different conditional scenarios and improving your scripting skills.