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.

disk-if-else.sh
#!/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
✓ What this does, line by line

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:

terminal
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:

PartSyntaxPurpose
ifif [ condition ]; thenFirst test — runs when true
elifelif [ condition ]; thenSecond test — only if previous tests failed
elseelseFallback — runs when no test matched
fifiCloses the entire block — do not forget this

Step 3 — Make it executable

terminal
chmod +x disk-if-else.sh

You only need to do this once. It gives the script permission to run.

Step 4 — Run it

terminal
./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

terminal
crontab -e

Add one of these lines

crontab
# 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
💡 Tip: Use crontab.guru

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:

string-compare.sh
#!/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:

file-exists.sh
#!/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 =:

integer-compare.sh
#!/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
If your site keeps going down, your hosting might be the problem. Namecheap shared hosting starts at $1.58/mo. Free domain, free SSL, 99.9% uptime guarantee. Switch before the next outage finds you first.
View Hosting Plans →
Run your if/else checks on a server 24/7 DigitalOcean droplets start at $4/month. Spin one up to run disk and health scripts around the clock — includes $200 free credit for new accounts.
Get $200 Free →
DigitalOcean Referral Badge

Common Mistakes

⚠ Forgetting spaces inside [ ]

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.

⚠ Using = instead of -eq for numbers

= 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.

⚠ Missing fi at the end

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 Tool
Build this into a full script template
Use the Bash Boilerplate Generator to wrap conditionals in a production-ready script with error handling, logging, and more.
Try the Generator → Browse All Tools

⚙️ Free Tools

Pair with the Cron Job Builder to schedule your disk if/else checks automatically.

Browse All Tools →

Related Snippets