Chapter 56: Bash If…Else
If…Else day
This is one of the most important topics in Bash scripting — without if…else, your scripts can only do one boring thing every time. With if…else, your script becomes smart: it can decide what to do based on conditions — like a real friend who says:
“If it’s raining, take umbrella. Else if it’s sunny, wear sunglasses. Else just go normally.”
In Bash, if…else lets your script ask questions and choose different paths.
Let’s learn it step-by-step, slow and clear, with lots of real examples you can type right now.
1. Basic Structure of if…else in Bash
There are three main forms — start with the simplest:
Form 1: Simple if (no else)
|
0 1 2 3 4 5 6 7 8 |
if [ condition ]; then # commands if condition is true fi |
- [ is actually a command (test command) — needs spaces around it
- ] closes the test
- then starts the block
- fi ends the block (if backwards)
Form 2: if…else
|
0 1 2 3 4 5 6 7 8 9 10 |
if [ condition ]; then # do this if true else # do this if false fi |
Form 3: if…elif…else (multiple choices)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
if [ condition1 ]; then # ... elif [ condition2 ]; then # ... elif [ condition3 ]; then # ... else # none of above fi |
2. The Most Important Part: Conditions (What Goes Inside [ ])
Bash uses the test command [ … ] to check things. Here are the most common test operators you will use 90% of the time:
| Operator | Meaning | Example inside [ ] | What it checks |
|---|---|---|---|
| -eq | Equal (numbers) | [ “$a” -eq “$b” ] | 5 -eq 5 → true |
| -ne | Not equal | [ “$a” -ne 10 ] | |
| -gt | Greater than | [ “$age” -gt 18 ] | |
| -ge | Greater or equal | [ “$marks” -ge 60 ] | |
| -lt | Less than | [ “$count” -lt 5 ] | |
| -le | Less or equal | [ “$files” -le 100 ] | |
| == | String equal | [ “$city” == “Hyderabad” ] | Better with [[ ]] |
| != | String not equal | [ “$answer” != “yes” ] | |
| -z | String is empty | [ -z “$name” ] | No characters |
| -n | String is not empty | [ -n “$email” ] | Has at least one character |
| -f | Exists and is regular file | [ -f “report.pdf” ] | |
| -d | Exists and is directory | [ -d “~/Documents” ] | |
| -e | Exists (file or folder) | [ -e “config.txt” ] | |
| -r | Readable | [ -r “secret.key” ] | Current user can read |
| -w | Writable | [ -w “log.txt” ] | |
| -x | Executable | [ -x “myscript.sh” ] | Can run as program |
Very important modern tip: Use [[ … ]] (double brackets) instead of single [ … ] whenever possible — it’s safer and more powerful.
|
0 1 2 3 4 5 6 7 8 9 10 |
# Old style (single brackets) – fragile if [ "$name" == "Rahul" ]; then ... # Modern & recommended (double brackets) if [[ "$name" == "Rahul" ]]; then ... |
Double [[ ]] advantages:
- No word splitting issues (safer with spaces)
- Supports == pattern matching (* ?)
- Can use && || inside without escaping
3. Real Examples – Type These Right Now!
Example 1: Simple if…else (age check)
Create file age_check.sh:
|
0 1 2 3 4 5 6 |
nano age_check.sh |
Paste:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#!/bin/bash echo "How old are you?" read age if [[ "$age" -ge 18 ]]; then echo "You are $age — you can vote! 🗳️" else echo "You are $age — too young to vote 😔" fi echo "Thank you for playing!" |
Run:
|
0 1 2 3 4 5 6 7 |
chmod +x age_check.sh ./age_check.sh |
Try typing 20, then 15 — see how it decides!
Example 2: if…elif…else (grade calculator)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#!/bin/bash echo "Enter your marks (0-100):" read marks if [[ "$marks" -ge 90 ]]; then echo "Grade: A+ 🎖️ Excellent!" elif [[ "$marks" -ge 80 ]]; then echo "Grade: A Very good!" elif [[ "$marks" -ge 70 ]]; then echo "Grade: B Good" elif [[ "$marks" -ge 60 ]]; then echo "Grade: C Average" else echo "Grade: F Need to study more 😢" fi |
Example 3: Check if file exists & is executable
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#!/bin/bash script="run_me.sh" if [[ -f "$script" && -x "$script" ]]; then echo "$script exists and is executable — running it now..." ./"$script" elif [[ -f "$script" ]]; then echo "$script exists but is NOT executable" echo "Fixing it for you..." chmod +x "$script" else echo "Error: $script not found!" exit 1 fi |
Example 4: String comparison & empty check
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#!/bin/bash echo "Enter your city:" read city if [[ -z "$city" ]]; then echo "You didn't enter anything!" elif [[ "$city" == "Hyderabad" || "$city" == "HYD" ]]; then echo "Namaste from home! 😄" elif [[ "$city" == "Delhi" ]]; then echo "Arre bhai, capital wale!" else echo "Nice to know you live in $city" fi |
Summary Table – if…else at a Glance
| Part | Syntax / Rule | Common Example |
|---|---|---|
| Basic if | if [[ condition ]]; then … fi | if [[ $age -ge 18 ]]; then … |
| if…else | if …; then … else … fi | else echo “Too young” |
| if…elif…else | elif [[ condition2 ]]; then … | elif [[ $marks -ge 80 ]]; then … |
| Numeric compare | -eq -ne -gt -ge -lt -le | [[ $a -gt $b ]] |
| String compare | == != -z -n | [[ “$str” == “yes” ]] |
| File test | -f -d -e -r -w -x | [[ -x “script.sh” ]] |
| Logical combine | && | |
| Recommended test | [[ … ]] | Safer than single [ … ] |
Teacher’s Golden Rules
- Always double-quote variables inside [[ ]]: “$var”
- Use [[ ]] instead of [ ] — modern, safer, more features
- Use (( )) for numeric math & comparisons when possible
- Always end with fi (if spelled backwards)
- Test conditions with [[ condition ]] && echo “True” || echo “False”
- Never forget spaces around [ and ] — [ is a command!
Got it, boss? if…else is how your script becomes intelligent — it asks questions, checks answers, and decides what to do next.
Any part confusing? Want next:
- “Teacher, explain case statement (like switch)”
- “How to use && and || shortcuts”
- “Nested if examples”
- “Test command deep dive [ vs [[ vs (( ”
- “Common if mistakes & how to debug”
Just say — teacher is ready in Hyderabad! Keep writing small if-else scripts every day — soon decisions will feel natural! 🐧❓✅😄
