If Statements
If statements allow your scripts to make decisions based on conditions. They're the foundation of conditional logic in Bash, enabling your scripts to respond differently based on values, file states, command results, and more. Understanding if statements is essential for writing dynamic, responsive shell scripts!
Basic If Statement
The simplest form of an if statement executes code only when a condition is true. The syntax uses if, then, and fi (if backwards).
Click Run to execute your code
# Basic syntax
if [ condition ]; then
# code to execute if condition is true
fi
# Example
age=18
if [ $age -ge 18 ]; then
echo "You are an adult"
fi
- Spaces around brackets are required:
[ condition ]-
then must be on same line with ; or on next line-
fi closes the if statement (if spelled backwards)- The condition uses test operators (covered in Operators module)
If-Else Statement
When you want to handle both true and false cases, use else to specify what happens when the condition is false.
if [ condition ]; then
# code if true
else
# code if false
fi
# Example
age=15
if [ $age -ge 18 ]; then
echo "You are an adult"
else
echo "You are a minor"
fi
If-Elif-Else Statement
For multiple conditions, use elif (else if) to chain conditions. Bash checks conditions in order and executes the first one that's true.
if [ condition1 ]; then
# code if condition1 is true
elif [ condition2 ]; then
# code if condition2 is true
elif [ condition3 ]; then
# code if condition3 is true
else
# code if all conditions are false
fi
# Example: Grade calculation
score=85
if [ $score -ge 90 ]; then
grade="A"
elif [ $score -ge 80 ]; then
grade="B"
elif [ $score -ge 70 ]; then
grade="C"
else
grade="F"
fi
elif conditions matters! Bash stops checking once it finds a true condition. Place more specific conditions first and broader ones later.
Single-Line If Statement
For simple conditions, you can write if statements on a single line. This is useful for quick checks and is common in shell scripts.
# Single-line if
if [ condition ]; then command; fi
# Using && and || operators
[ condition ] && command_if_true || command_if_false
# Examples
[ -f file.txt ] && echo "File exists"
[ $age -ge 18 ] && echo "Adult" || echo "Minor"
# Common pattern
[ -d "/tmp" ] && rm -rf /tmp/* || echo "Directory not found"
&& and || can be confusing. The || part executes if the command fails, which might not always be what you expect. Use multi-line if statements for clarity when logic is complex!
Nested If Statements
You can place if statements inside other if statements to create complex conditional logic. Each nested if needs its own fi.
# Nested if example
age=25
if [ $age -ge 18 ]; then
echo "Adult"
if [ $age -ge 65 ]; then
echo "Senior citizen"
else
echo "Regular adult"
fi
else
echo "Minor"
fi
- Each
if must have a matching fi- Proper indentation makes nested ifs readable
- Consider using
elif instead of nested ifs when possible (often clearer)
Advanced: Using [[ ]] Instead of [ ]
Bash provides two ways to test conditions: [ ] (POSIX compatible) and [[ ]] (Bash-specific, more powerful).
Click Run to execute your code
| Feature | [ ] (test) | [[ ]] (Bash) |
|---|---|---|
| Pattern matching | No | Yes ([[ $var == *.txt ]]) |
| Regex matching | No | Yes ([[ $var =~ regex ]]) |
| Logical operators | -a, -o |
&&, || |
| Variable handling | Quotes needed | Safer without quotes |
| Portability | POSIX standard | Bash-specific |
# [[ ]] advantages
filename="test.txt"
# Pattern matching
if [[ $filename == *.txt ]]; then
echo "Text file"
fi
# Regex matching
if [[ $email =~ ^[a-zA-Z0-9._%+-]+@ ]]; then
echo "Valid email"
fi
# Logical operators
if [[ -f "$file" && -r "$file" ]]; then
echo "File exists and is readable"
fi
Common Mistakes
1. Missing spaces around brackets
# Wrong - no spaces
if [$age -ge 18]; then # Syntax error!
# Correct - spaces required
if [ $age -ge 18 ]; then
echo "Adult"
fi
2. Using = instead of -eq for numbers
# Wrong - = compares strings
if [ $count = 5 ]; then # Works but string comparison
# Correct - -eq for numeric comparison
if [ $count -eq 5 ]; then # Proper numeric comparison
# For strings, = is correct
if [ "$name" = "Alice" ]; then # String comparison
3. Forgetting then on new line
# Wrong - missing semicolon
if [ condition ]
then # Error if then is on next line without proper syntax
# Correct - semicolon or then on same line
if [ condition ]; then
command
fi
# Or then on next line (needs proper formatting)
if [ condition ]
then
command
fi
4. Using assignment in condition
# Wrong - assignment, not comparison
if [ $count = 5 ]; then # Actually assigns (in some contexts)
# Correct - use == or -eq
if [ $count -eq 5 ]; then # Comparison
if [[ $count == 5 ]]; then # Comparison
# For string comparison
if [ "$name" = "Alice" ]; then # String comparison (single =)
if [[ "$name" == "Alice" ]]; then # String comparison (==)
Exercise: Create a Decision Script
Task: Create a script that makes decisions based on conditions!
Requirements:
- Create a variable for age
- Use if-elif-else to categorize: child (0-12), teenager (13-17), adult (18-64), senior (65+)
- Check if a file exists and print appropriate message
- Use nested if to check both age and a status variable
- Include at least one single-line if statement
Show Solution
#!/bin/bash
# Decision script
age=25
status="active"
# Age categorization
if [ $age -le 12 ]; then
category="child"
elif [ $age -le 17 ]; then
category="teenager"
elif [ $age -le 64 ]; then
category="adult"
else
category="senior"
fi
echo "Age $age: $category"
# File check
[ -f /etc/passwd ] && echo "File exists" || echo "File not found"
# Nested if
if [ $age -ge 18 ]; then
if [ "$status" = "active" ]; then
echo "Active adult"
else
echo "Inactive adult"
fi
fi
Summary
- Basic If:
if [ condition ]; then ... fi - If-Else:
if ... else ... fihandles true and false cases - Elif: Chain multiple conditions with
elif - Single-Line:
if [ cond ]; then cmd; fior[ cond ] && cmd - Nested: If statements can contain other if statements
- Spaces: Always use spaces around brackets:
[ condition ] - [[ ]] vs [ ]:
[[ ]]is Bash-specific and more powerful - Operators: Use
-eq,-nefor numbers;=,!=for strings
What's Next?
Great job mastering if statements! Next, we'll learn about Case Statements - a cleaner alternative to long if-elif chains when checking a single variable against multiple values. Case statements are perfect for menu systems and command parsing!
Enjoying these tutorials?