if / else Conditions
if statements let a script make decisions based on tests.
Syntax
if [ condition ]; then
...
fiAn if statement runs commands only when a test succeeds. In bash the test goes inside square brackets, and the block ends with fi.
Structure
if [ condition ]; then
# ...
elif [ other ]; then
# ...
else
# ...
fiCommon tests
-f file— the file exists.-d dir— the directory exists.-z "$var"— the string is empty."$a" = "$b"— strings are equal.$a -eq $b,-gt,-lt— numeric equal, greater, less.
Example
#!/bin/bash
file="config.txt"
if [ -f "$file" ]; then
echo "$file exists"
else
echo "$file is missing, creating it"
touch "$file"
fi
# Numeric comparison
count=5
if [ "$count" -gt 3 ]; then
echo "More than three"
fiWhen to use it
- A deployment script checks 'if [ -f /opt/app/config.yaml ]' before starting the app, exiting early with a clear error if config is missing.
- A cron job uses 'if [ $DISK_PCT -gt 85 ]' to send an alert email only when disk usage exceeds a threshold.
- A script checks 'if command -v docker &>/dev/null' to test whether Docker is installed before attempting to run containers.
More examples
If-else with string test
Demonstrates if/elif/else for branching on a string variable value, using the [ ] test command.
#!/bin/bash
ENV=${1:-"dev"}
if [ "$ENV" = "production" ]; then
echo "Running in PRODUCTION mode"
elif [ "$ENV" = "staging" ]; then
echo "Running in staging mode"
else
echo "Running in dev mode"
fiTest file existence
Uses -f to test for a regular file and ! to negate it, exiting early with an error if a required file is missing.
#!/bin/bash
CONFIG="/etc/myapp/config.yaml"
if [ ! -f "$CONFIG" ]; then
echo "Error: config not found at $CONFIG" >&2
exit 1
fi
echo "Config found, starting app..."Numeric comparison
Reads disk usage into a variable and uses -gt numeric comparison to trigger different alert levels.
#!/bin/bash
DISK_PCT=$(df / | awk 'NR==2 {print $5}' | tr -d '%')
if [ "$DISK_PCT" -gt 90 ]; then
echo "CRITICAL: disk at ${DISK_PCT}%" | mail -s 'Disk Alert' [email protected]
elif [ "$DISK_PCT" -gt 75 ]; then
echo "WARNING: disk at ${DISK_PCT}%"
fi
Discussion