If/Else Statements
Conditional statements allow your scripts to make decisions and execute different code paths based on conditions. The if statement is the foundation of flow control in bash.
Basic If Syntax
The simplest form of an if statement:
if [ condition ]; then
commands
fi
The spaces inside [ ] are required!
#!/bin/bash
AGE=18
if [ "$AGE" -ge 18 ]; then
echo "You are an adult"
fi
If-Else
Execute alternative code when the condition is false:
if [ condition ]; then
# runs when true
commands
else
# runs when false
other_commands
fi
Example:
#!/bin/bash
FILE="test.txt"
if [ -f "$FILE" ]; then
echo "File exists"
else
echo "File not found"
fi
If-Elif-Else
Handle multiple conditions:
if [ condition1 ]; then
commands1
elif [ condition2 ]; then
commands2
elif [ condition3 ]; then
commands3
else
default_commands
fi
Example:
#!/bin/bash
SCORE=85
if [ "$SCORE" -ge 90 ]; then
echo "Grade: A"
elif [ "$SCORE" -ge 80 ]; then
echo "Grade: B"
elif [ "$SCORE" -ge 70 ]; then
echo "Grade: C"
else
echo "Grade: F"
fi
Exercise: If-Else Statement
Write a simple conditional:
The [ ] Test Command
[ ] is actually a command called test. These are equivalent:
if [ "$A" -eq 5 ]; then echo "Yes"; fi
if test "$A" -eq 5; then echo "Yes"; fi
Important rules:
- Spaces after
[and before]are required - Always quote variables:
"$VAR"
The [[ ]] Extended Test
[[ ]] is a bash improvement over [ ]:
# [[ ]] advantages:
# - No word splitting on variables
# - Pattern matching with ==
# - Regex matching with =~
# - Logical && and || inside
if [[ $NAME == "admin" ]]; then
echo "Welcome admin"
fi
# Pattern matching
if [[ $FILE == *.txt ]]; then
echo "Text file"
fi
# Regex matching
if [[ $EMAIL =~ ^[a-z]+@[a-z]+\.[a-z]+$ ]]; then
echo "Valid email"
fi
[ ] vs [[ ]]
| Feature | [ ] | [[ ]] |
|---|---|---|
| POSIX compatible | Yes | No (bash only) |
| Word splitting | Yes | No |
| Pattern matching | No | == with patterns |
| Regex matching | No | =~ |
| Logical operators | -a, -o | &&, || |
Recommendation: Use [[ ]] in bash scripts for safety and features.
Combining Conditions
With [ ]
# AND
if [ "$A" -gt 5 ] && [ "$B" -lt 10 ]; then
echo "Both conditions true"
fi
# OR
if [ "$A" -gt 5 ] || [ "$B" -lt 10 ]; then
echo "At least one true"
fi
# NOT
if [ ! -f "$FILE" ]; then
echo "File does not exist"
fi
With [[ ]]
# AND (cleaner syntax)
if [[ $A -gt 5 && $B -lt 10 ]]; then
echo "Both conditions true"
fi
# OR
if [[ $A -gt 5 || $B -lt 10 ]]; then
echo "At least one true"
fi
Negating Conditions
Use ! to negate:
# File does NOT exist
if [ ! -f "$FILE" ]; then
echo "File missing"
fi
# String is NOT empty
if [ ! -z "$VAR" ]; then
echo "Variable is set"
fi
# NOT equal
if [ "$A" != "$B" ]; then
echo "Values differ"
fi
Nested If Statements
If statements can contain other if statements:
#!/bin/bash
AGE=25
HAS_LICENSE=true
if [ "$AGE" -ge 18 ]; then
if [ "$HAS_LICENSE" = true ]; then
echo "You can drive"
else
echo "You need a license"
fi
else
echo "Too young to drive"
fi
Exercise: Combined Conditions
Use multiple conditions:
One-Line Conditionals
For simple cases, use && and ||:
# If true, do this
[ -f "$FILE" ] && echo "File exists"
# If false, do this
[ -f "$FILE" ] || echo "File missing"
# Combined
[ -f "$FILE" ] && echo "Found" || echo "Missing"
Arithmetic Conditionals
Use (( )) for arithmetic:
#!/bin/bash
X=10
if (( X > 5 )); then
echo "X is greater than 5"
fi
if (( X >= 5 && X <= 15 )); then
echo "X is between 5 and 15"
fi
# Increment and check
if (( ++X == 11 )); then
echo "X is now 11"
fi
Common Patterns
Check if variable is set
if [ -n "${VAR+x}" ]; then
echo "VAR is set"
fi
# Or simpler
if [ -n "$VAR" ]; then
echo "VAR is set and non-empty"
fi
Check command success
if command; then
echo "Command succeeded"
else
echo "Command failed"
fi
# Real example
if grep -q "pattern" file.txt; then
echo "Pattern found"
fi
Default values with conditionals
if [ -z "$NAME" ]; then
NAME="default"
fi
# Or shorter
[ -z "$NAME" ] && NAME="default"
# Or even shorter
NAME="${NAME:-default}"
Key Takeaways
- Use
if [ condition ]; then ... fifor basic conditionals - Always quote variables inside
[ ] - Use
[[ ]]in bash for advanced features and safety - Combine conditions with
&&(AND) and||(OR) - Negate conditions with
! - Use
eliffor multiple exclusive conditions - Use
(( ))for arithmetic comparisons - One-liner:
[ condition ] && true_command || false_command

