Part 3: Control Structures in Bash (if, for, while, case, break, continue)
Introduction
Control structures are what make your Bash scripts intelligent, dynamic, and able to make decisions.
With these tools, your script can:
- Check if a file exists
- Loop through lists or directories
- Perform repeated tasks
- Match patterns
- Break or skip loops when needed
This part is crucial because automation begins with conditions + loops.
🧠 SECTION 1 — IF, ELSE, ELIF (Conditional Statements)
🔹 Basic Syntax
if [ condition ]; then
# commands
fi🔹 Example: Check if a File Exists
file="data.txt"
if [ -f "$file" ]; then
echo "File $file exists."
else
echo "File $file not found."
fiCommon File Conditions
| Condition | Meaning |
|---|---|
-f | File exists |
-d | Directory exists |
-e | File or directory exists |
-r | Readable |
-w | Writable |
-x | Executable |
🔹 Using elif
num=20
if [ $num -gt 50 ]; then
echo "Number is greater than 50"
elif [ $num -gt 10 ]; then
echo "Number is greater than 10"
else
echo "Number is 10 or less"
fi🔹 Comparison Operators
| Operator | Meaning |
|---|---|
-eq | Equal |
-ne | Not equal |
-gt | Greater than |
-lt | Less than |
-ge | Greater or equal |
-le | Less or equal |
🧠 SECTION 2 — FOR LOOPS
Used to repeat actions for a list.
🔹 Loop Through Numbers
for i in {1..5}
do
echo "Count: $i"
done🔹 Loop Through Files in Directory
for file in *.txt
do
echo "Processing $file"
done
🔹 Loop Through an Array
fruits=("apple" "banana" "mango")
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done🧠 SECTION 3 — WHILE LOOPS
Repeat until condition becomes false.
🔹 Example: Print Numbers 1 to 5
count=1
while [ $count -le 5 ]
do
echo "Count: $count"
count=$((count+1))
done🔹 Monitor a Log File Until a Keyword Appears
while true
do
if grep -q "ERROR" app.log; then
echo "Error found in log!"
break
fi
sleep 3
doneThis is used often for server monitoring scripts.
🧠 SECTION 4 — UNTIL LOOPS
Opposite of while: runs until condition is true.
x=1
until [ $x -gt 5 ]
do
echo "x = $x"
x=$((x+1))
done🧠 SECTION 5 — CASE STATEMENT
Better than long if-else chains. Useful for menus.
🔹 Example: User Menu
echo "Choose an option:"
echo "1) Show date"
echo "2) List files"
echo "3) Show current user"
read choice
case $choice in
1)
date
;;
2)
ls -l
;;
3)
whoami
;;
*)
echo "Invalid option!"
;;
esac🧠 SECTION 6 — LOOP CONTROL: BREAK & CONTINUE
🔹 BREAK — Stop the loop
for i in {1..10}
do
if [ $i -eq 5 ]; then
break
fi
echo "Number: $i"
done
🔹 CONTINUE — Skip current iteration
for i in {1..5}
do
if [ $i -eq 3 ]; then
continue
fi
echo "Value: $i"
done
🧰 Real-World Automation Example: Clean Old Log Files
#!/bin/bash
log_dir="/var/log/myapp"
for file in "$log_dir"/*.log
do
if [ -f "$file" ]; then
size=$(stat -c%s "$file")
if [ $size -gt 500000 ]; then
echo "Rotating $file ..."
mv "$file" "$file.old"
fi
fi
done✔️ Very useful in server maintenance scripts (DevOps).
🧰 Bonus: Server Health Check Script
#!/bin/bash
echo "Checking server health..."
echo "---------------------------"
# CPU usage
cpu=$(top -bn1 | grep "Cpu" | awk '{print $2}')
echo "CPU Usage: $cpu%"
# Memory
mem=$(free -m | awk 'NR==2{printf "%s/%sMB (%.2f%%)", $3,$2,$3*100/$2 }')
echo "Memory: $mem"
# Disk
disk=$(df -h / | awk 'NR==2{print $5}')
echo "Disk Usage: $disk"
# Check service
if systemctl is-active --quiet nginx; then
echo "Nginx: Running"
else
echo "Nginx: Not Running"
fiSummary
In Part 3, you learned:
✅ if, elif, else
✅ Numeric and file comparisons
✅ for, while, and until loops
✅ case pattern matching
✅ break & continue
✅ Real-world automation examples
These are the core fundamentals of every automation script in Bash.
🔜 Next in Series
👉 Part 4: Working with Files & Directories (grep, sed, awk, permissions, redirects, pipes)
This part includes powerful text-processing commands used in DevOps & Linux admin work.
