Bash If/Else Examples

conditionalsbasicsif
4 min read

Quick Answer

A bash if statement tests whether a command exits with code 0 (success) or non-zero (failure). The test command — written as [ condition ] — evaluates comparisons and file checks. The full structure is: if [ condition ]; then ... elif [ condition ]; then ... else ... fi. Spaces inside the brackets are mandatory. For integers use -eq (equal), -gt (greater than), -lt (less than). For strings use = and !=. For files use -f (regular file exists), -d (directory exists), -e (either exists). A common mistake is using = for numbers — [ 5 = 10 ] does string comparison and gives unpredictable results with numbers. Always quote variables: [ "$VAR" = "value" ] handles empty strings safely where [ $VAR = "value" ] would cause a syntax error. Works in bash on Ubuntu 22.04 LTS, Debian 12, Fedora 39, CentOS 9, and macOS Ventura.

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.

bash
#!/bin/bash # Script: disk-if-else.sh # Purpose: Classify disk usage into critical, warning, or OK — three-branch if/elif/else # Usage: ./disk-if-else.sh set -euo pipefail CHECK="✓" CROSS="✗" THRESHOLD=80 CRITICAL=90 PARTITION="/" USAGE=$(df "$PARTITION" | awk 'NR==2{print $5}' | tr -d '%') if [ "$USAGE" -gt "$CRITICAL" ]; then echo "$CROSS CRITICAL: Disk at ${USAGE}% — free space immediately" elif [ "$USAGE" -gt "$THRESHOLD" ]; then echo "$CROSS WARNING: Disk at ${USAGE}% — above ${THRESHOLD}% threshold" else echo "$CHECK OK: Disk at ${USAGE}% (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:

bash
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

bash
chmod +x disk-if-else.sh

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

Step 4 — Run it

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

bash
crontab -e

Add one of these lines

bash
# 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:

bash
#!/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:

bash
#!/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 =:

bash
#!/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

Bash Comparison Operator Quick Reference

TypeOperatorMeaning
Integer-eqEqual
Integer-neNot equal
Integer-gtGreater than
Integer-ltLess than
Integer-geGreater than or equal
Integer-leLess than or equal
String=Equal
String!=Not equal
String-zEmpty string
String-nNon-empty string
File-fRegular file exists
File-dDirectory exists
File-eFile or directory exists

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

Use = for string comparisons. 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

How do I write an if/else statement in bash?

The basic structure is: if [ condition ]; then ... else ... fi. The spaces around the condition inside [ ] are mandatory — [ "$x" = "y" ] works, ["$x" = "y"] does not.

What is the difference between [ ] and [[ ]] in bash?

[ ] is POSIX-compliant and works in all shells. [[ ]] is a bash extension with additional features: regex matching with =~, no word splitting on unquoted variables, and &&/|| instead of -a/-o. Use [[ ]] in bash-only scripts when you need those features.

How do I compare numbers in a bash if statement?

Use integer comparison operators inside [ ]: -eq (equal), -ne (not equal), -gt (greater than), -lt (less than). Do not use = for numbers — [ 5 = 10 ] does string comparison and can give wrong results.

How do I check if a variable is empty in bash?

Use [ -z "$VAR" ] to test for empty, or [ -n "$VAR" ] for non-empty. Always quote the variable — without quotes, an empty string causes a syntax error in the test.

Why does bash say "command not found" inside an if statement?

The most common cause is a missing then keyword or unquoted variable. Every if line must end with ; then. Check for: missing spaces inside [ ], missing fi at the end, and unquoted variables that contain spaces.

BashSnippets logo

Written by Anguishe

Creator of BashSnippets.xyz

bashsnippets.xyz/about

Run this script on a real Linux server

Get $200 free credit — DigitalOcean

Get $200 Free →

Affiliate link · we earn a commission

Need a domain for your next project?

Register with Namecheap — free WHOIS privacy included

Check Domain Prices →

Affiliate link · we earn a commission

Related Snippets

Frequently Asked Questions

How do I run this script?

Save the if/else examples as conditionals.sh, run chmod +x conditionals.sh, then execute ./conditionals.sh.

Does this work on macOS?

Yes. [ ] and [[ ]] test syntax works on macOS bash and zsh. Quote all variables inside brackets.

How do I write an if/else statement in bash?

Use if [ condition ]; then ... elif [ condition ]; then ... else ... fi. Spaces inside brackets are mandatory.

How do I compare numbers in a bash if statement?

Use -eq, -gt, -lt for integers inside [ ]. Never use = for numeric comparison — that does string comparison.