Shell Scripting: Mastering Conditions (if, elif, else)
What Are Conditions in Shell?
In Shell scripting, conditions let you:
✅ Check if something is true or false
✅ Make decisions inside your scripts
Instead of running blindly, your script thinks at every step.
🛠️ Basic Syntax
#!/bin/bash
if [ condition ]; then
commands
elif [ another_condition ]; then
commands
else
commands
fi
✅ Important:
📚 Example 1: Simple if
#!/bin/bash
disk_usage=85
if [ "$disk_usage" -gt 80 ]; then
echo "Warning: Disk usage above 80%!"
fi
✅ Checks if disk_usage is greater than 80%.
📚 Example 2: if...else
#!/bin/bash
server_status="down"
if [ "$server_status" = "up" ]; then
echo "Server is running."
else
echo "Server is down."
fi
✅If condition is true → one block runs.
Else → another block runs.
📚 Example 3: if...elif...else
#!/bin/bash
memory_usage=65
if [ "$memory_usage" -gt 90 ]; then
echo "Critical: Memory usage very high!"
elif [ "$memory_usage" -gt 70 ]; then
echo "Warning: Memory usage moderately high."
else
echo "Memory usage is normal."
fi
✅ Multiple layers of conditions = smarter decision trees.
Observability Real-World Example
✅ A script to alert based on CPU Load:
#!/bin/bash
cpu_load=$(uptime | awk -F'load average:' '{ print $2 }' | cut -d',' -f1 | sed 's/ //g')
cpu_load_int=${cpu_load%.*} # Remove decimal part
if [ "$cpu_load_int" -gt 8 ]; then
echo "Critical Alert: CPU load too high!"
elif [ "$cpu_load_int" -gt 4 ]; then
echo "Warning: CPU load moderate."
else
echo "CPU load normal."
fi
✅ Smart automation: Different actions depending on CPU load.
🗺️ Where Are We in the Journey?
Linux Fundamentals → Kubernetes Observability → Shell Basics → (Now) Conditions → Loops → Functions
✅
You are learning to make your scripts think like engineers.