Menu

Saturday, 1 November 2025

🧩Shell Scripting for Beginners – Part 3: Conditional Statements (if, elif, else)

🚦 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

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: -5
Negative 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.sh
File 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/tomcat
Directory 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: devops
User 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): prod
Deploying 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 directory
Script 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