π¦ Shell Scripting for Beginners – Part 3: Conditional Statements (if, elif, else)
Welcome to Part 3 of the MiddlewareBox Shell Scripting Series!
In this chapter, we’ll learn how your script can make decisions using if, elif, and else.
These are the “logic gates” of automation. π¦
π Table of Contents
- π‘ Basic Syntax
- π― Example 1 – Number Check
- ⚙️ Example 2 – File Existence
- π¦ Example 3 – Directory Check
- π§ Example 4 – User Login
- π§° Example 5 – Tomcat Status
- πΎ Example 6 – Disk Usage Warning
- π Example 7 – Deployment Logic
- π Example 8 – Jenkins Job Check
- π§© Example 9 – Server Health Monitor
- ⚠️ What Happens When a Command Fails?
- π§ Example 10 – File Read Failure
- π§° Example 11 – Jenkins Trigger Failure
- πΎ Example 12 – Stop Script on Failure (set -e)
- π Conclusion
π‘ Basic Syntax
if [ condition ]; then
commands
elif [ another_condition ]; then
commands
else
commands
fi
π¬ Concept:
✅ True → runs block; ❌ False → moves to next or else.π― Example 1: Simple Number Check
#!/bin/bash
read -p "Enter a number: " num
if [ $num -gt 0 ]; then
echo "Positive number"
elif [ $num -lt 0 ]; then
echo "Negative number"
else
echo "Zero"
fi
π¬ Output:
Enter a number: -5Negative number
⚙️ Example 2: Check File Existence
#!/bin/bash
read -p "Enter file name: " file
if [ -f "$file" ]; then
echo "File exists ✅"
else
echo "File not found ❌"
fi
π¬ Output:
Enter file name: test.shFile exists ✅
π¦ Example 3: Directory Check
#!/bin/bash
read -p "Enter directory path: " dir
if [ -d "$dir" ]; then
echo "Directory exists π"
else
echo "Directory not found π«"
fi
π¬ Output:
Enter directory path: /opt/tomcatDirectory exists π
π§ Example 4: Check User Login
#!/bin/bash
read -p "Enter username: " user
if id "$user" &>/dev/null; then
echo "User $user exists π€"
else
echo "User $user not found ⚠️"
fi
π¬ Output:
Enter username: devopsUser devops exists π€
π§° Example 5: Tomcat Status Checker
#!/bin/bash
pid=$(pgrep -f "org.apache.catalina.startup.Bootstrap")
if [ -n "$pid" ]; then
echo "Tomcat is running (PID: $pid) ✅"
else
echo "Tomcat is not running ❌"
fi
π¬ Output:
Tomcat is running (PID: 2145) ✅πΎ Example 6: Disk Space Warning
#!/bin/bash
use=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
if [ $use -ge 90 ]; then
echo "π¨ Disk almost full: ${use}%"
elif [ $use -ge 70 ]; then
echo "⚠️ Disk usage high: ${use}%"
else
echo "✅ Disk usage normal: ${use}%"
fi
π¬ Output:
⚠️ Disk usage high: 75%π Example 7: Deployment Environment Logic
#!/bin/bash
read -p "Enter environment (dev/test/prod): " env
if [ "$env" == "dev" ]; then
echo "Deploying to Development π§"
elif [ "$env" == "test" ]; then
echo "Deploying to QA π§ͺ"
elif [ "$env" == "prod" ]; then
echo "Deploying to Production ⚙️"
else
echo "Invalid environment ❌"
fi
π¬ Output:
Enter environment (dev/test/prod): prodDeploying to Production ⚙️
π Example 8: Jenkins Job Success Check
#!/bin/bash
status=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8080/job/myjob/lastBuild/api/json)
if [ "$status" == "200" ]; then
echo "✅ Jenkins job ran successfully."
else
echo "❌ Jenkins job failed or not accessible."
fi
π¬ Output:
✅ Jenkins job ran successfully.π§© Example 9: Server Health Monitor
#!/bin/bash
ping -c1 google.com &>/dev/null
if [ $? -eq 0 ]; then
echo "π Internet reachable."
else
echo "π« No network connection."
fi
π¬ Output:
π Internet reachable.⚠️ What Happens When a Command Fails?
Every command returns an exit code:
0 → success ✅ | non-zero → failure ❌
$? stores this code.
if uses it automatically to decide what to do next.
π§ Example 10: File Read Failure Handling
#!/bin/bash
cat /etc/nofile &>/dev/null
if [ $? -eq 0 ]; then
echo "✅ File read successful"
else
echo "❌ Command failed with exit code $?"
fi
π¬ Output:
❌ Command failed with exit code 1π§° Example 11: Jenkins Trigger Failure
#!/bin/bash
curl -s -o /dev/null -w "%{http_code}" http://localhost:8080/job/demo/build
if [ $? -eq 0 ]; then
echo "✅ Jenkins triggered."
else
echo "π¨ Jenkins trigger failed. Check server or credentials."
fi
π₯ Output (Jenkins down):
π¨ Jenkins trigger failed. Check server or credentials.πΎ Example 12: Stop Script on Any Failure (set -e)
#!/bin/bash
set -e
echo "Step 1: Creating directory..."
mkdir /tmp/demo_dir
echo "Step 2: Moving file..."
mv /file/does/not/exist /tmp/demo_dir
echo "✅ Script completed."
π¬ Output:
bash: mv: No such file or directoryScript exits immediately (set -e stops execution)
π Conclusion
- if → runs when condition succeeds (exit 0)
- elif → alternate logic branch
- else → fallback on failure
$?&set -e→ help handle failures cleanly
π― You now understand conditional logic like a DevOps pro!
No comments:
Post a Comment