Bash If Else — Complete Examples for Beginners
if [ condition ]; then ... elif [ condition ]; then ... else ... fi syntax.
Conditions use -eq for numbers, = for strings, and -f for files.
Tested on: Ubuntu 22.04 LTS · macOS Ventura
Every useful bash script branches on conditions — disk full or not, file exists or not, user said yes or no.
This page walks through if, elif, and else with a real disk-space checker you can run today,
then shows the three comparison types beginners need most.
The Script
Copy this into disk-if-else.sh. It uses if, elif, and else to classify disk usage into three levels — the same pattern as our disk space warning snippet, with an extra critical branch.
#!/bin/bash # Bash If / Elif / Else — disk space example # Three branches: critical, warning, or OK. # # USAGE: ./disk-if-else.sh # REQUIRES: bash, df, awk, tr (pre-installed on Linux/macOS) THRESHOLD=80 # ← warn at this % CRITICAL=90 # ← critical alert at this % PARTITION="/" # ← partition to check USAGE=$(df "$PARTITION" | awk 'NR==2{print $5}' | tr -d '%') if [ "$USAGE" -gt "$CRITICAL" ]; then echo "🔴 CRITICAL: Disk at ${USAGE}% — free space immediately" elif [ "$USAGE" -gt "$THRESHOLD" ]; then echo "⚠ WARNING: Disk at ${USAGE}% — above ${THRESHOLD}% threshold" else echo "✓ Disk OK: ${USAGE}% used (warn: ${THRESHOLD}%, critical: ${CRITICAL}%)" fi
THRESHOLD and CRITICAL set the two cutoffs. USAGE reads the current disk percent from df. The first if handles the worst case. elif runs only when the first test failed — still high, but not critical. else covers everything else. fi closes the block — always required.
Step-by-Step Setup
Step 1 — Create the file
Open a terminal and run:
nano disk-if-else.sh
Paste the script above, then press Ctrl+X → Y → Enter to save.
Step 2 — Understand the if/elif/else shape
Every branch follows the same pattern — spaces matter:
| Part | Syntax | Purpose |
|---|---|---|
| if | if [ condition ]; then | First test — runs when true |
| elif | elif [ condition ]; then | Second test — only if previous tests failed |
| else | else | Fallback — runs when no test matched |
| fi | fi | Closes the entire block — do not forget this |
Step 3 — Make it executable
chmod +x disk-if-else.sh
You only need to do this once. It gives the script permission to run.
Step 4 — Run it
./disk-if-else.sh
You should see one of three messages depending on how full your disk is right now.
Schedule It with Cron
Disk checks only help if they run automatically. Add the script to cron so you catch problems before the drive fills.
Open your crontab
crontab -e
Add one of these lines
# Check every day at 8am 0 8 * * * /home/user/disk-if-else.sh # Check every hour 0 * * * * /home/user/disk-if-else.sh # Log output to a file 0 8 * * * /home/user/disk-if-else.sh >> /var/log/diskcheck.log 2>&1
Go to crontab.guru to build and test cron time expressions for free. It explains exactly when your job will run in plain English.
Variations
String comparison (= and !=)
Use = and != inside [ ] for text. Quote variables so empty values do not break the test:
#!/bin/bash ENV="production" if [ "$ENV" = "production" ]; then echo "Running production config" elif [ "$ENV" = "staging" ]; then echo "Running staging config" else echo "Unknown environment: $ENV" fi
Check if a file exists (-f)
-f returns true only for regular files. Use -d for directories and -e for either:
#!/bin/bash CONFIG="/etc/myapp/config.yml" if [ -f "$CONFIG" ]; then echo "Config found — loading $CONFIG" else echo "Config missing — creating default at $CONFIG" touch "$CONFIG" fi
Integer comparison (-eq, -gt, -lt)
Numbers inside [ ] need numeric operators, not =:
#!/bin/bash COUNT=42 if [ "$COUNT" -eq 0 ]; then echo "No items" elif [ "$COUNT" -lt 10 ]; then echo "Low count: $COUNT" else echo "Count is $COUNT" fi
Common Mistakes
Bash requires spaces around brackets and operators. if [ "$x" -eq 5 ] works. if ["$x"-eq 5] fails with a syntax error. The [ command needs each piece as a separate argument.
= compares strings. For integers use -eq, -ne, -gt, -lt. Writing if [ "$USAGE" = 80 ] can behave unexpectedly — use -gt for greater-than checks like disk percentages.
Every if block must end with fi (if spelled backwards). Without it, bash reports syntax error: unexpected end of file. Nested ifs need a fi for each level.
Frequently Asked Questions
What is the syntax for if else in bash?
Write if [ condition ]; then commands, optionally elif [ condition ]; then for more branches, then else for the default, and close with fi. Example: if [ "$x" -gt 10 ]; then echo big; else echo small; fi.
Why does my bash if statement always fail?
Almost always missing spaces inside the brackets, or an unquoted empty variable. Always quote variables: [ "$FILE" -f ] not [ $FILE -f ]. Run bash -n script.sh to check syntax without executing.
When should I use elif instead of else?
Use elif when you have three or more distinct outcomes checked in order — like critical vs warning vs OK disk levels. Use plain else only for the final catch-all when no earlier condition matched.
Should I use single brackets [ ] or double brackets [[ ]]?
Beginners should stick with [ ] — it works everywhere and matches most tutorials. [[ ]] is a bash extension with slightly nicer string rules; both need spaces. Either way, always end with fi.
⚙️ Free Tools
Pair with the Cron Job Builder to schedule your disk if/else checks automatically.
Browse All Tools →