Menu

Saturday, 1 November 2025

๐Ÿ” Shell Scripting for Beginners – Part 4: Loops in Shell (for, while, until)

  • In this part, you'll learn how loops help automate Middleware & DevOps tasks — from restarting Tomcat, cleaning WebSphere logs, checking NGINX uptime, or retrying Jenkins jobs.
  • We'll also cover how to detect and handle errors inside loops ๐Ÿ’ฃ so your scripts don't fail silently.

๐Ÿ“‘ Table of Contents


1️⃣ The for Loop

The for loop executes a set of commands repeatedly for a list of items — servers, log files, users, etc. Perfect for middleware jobs like mass restarts or file cleanups.

๐ŸŽฏ Example 1: Basic For Loop

#!/bin/bash
for i in 1 2 3 4 5
do
  echo "Iteration number: $i"
done
๐Ÿ’ฌ Output:
Iteration number: 1
Iteration number: 2
...
Iteration number: 5

๐Ÿ’ผ Example 2: Rotate WebSphere Logs

#!/bin/bash
log_dir="/opt/IBM/WebSphere/AppServer/logs"
for file in $log_dir/*.log
do
  echo "Archiving: $file"
  gzip "$file" || echo "⚠️ Failed to compress $file"
done
echo "✅ WebSphere logs rotated successfully!"
๐Ÿ’ฌ Output:
Archiving: SystemOut.log
Archiving: SystemErr.log
✅ WebSphere logs rotated successfully!
⚠️ If a log file is locked by WebSphere, gzip fails. Use lsof $file to check which process is holding it.

๐Ÿš€ Example 3: Deploy WAR to Multiple Tomcat Servers

#!/bin/bash
servers=("devtomcat" "testtomcat" "prodtomcat")
for srv in "${servers[@]}"
do
  echo "Deploying to $srv..."
  scp myapp.war $srv:/opt/tomcat/webapps/ || {
    echo "❌ Deployment failed on $srv, skipping..."
    continue
  }
  ssh $srv "systemctl restart tomcat"
done
echo "✅ Deployment completed."
๐Ÿ’ฌ Output:
Deploying to devtomcat...
Deploying to testtomcat...
✅ Deployment completed.
❌ If SSH fails or disk is full, the continue keyword skips to the next server safely.

๐Ÿ’ฃ Example 4: Handling Command Failures

#!/bin/bash
set -e
for s in server1 server2
do
  echo "Checking $s..."
  ssh $s "uptime" || { echo "⚠️ Error connecting to $s"; continue; }
done
echo "✅ All servers checked."
๐Ÿง  Use set -e to exit immediately on error or || continue to skip failed items.

2️⃣ The while Loop

The while loop runs as long as a condition remains true — great for service monitoring and retries.

๐Ÿงฎ Example 5: Simple Counter

#!/bin/bash
count=1
while [ $count -le 5 ]
do
  echo "Count = $count"
  ((count++))
done

๐Ÿง  Example 6: Tomcat Health Check

#!/bin/bash
while true
do
  if pgrep -f "org.apache.catalina.startup.Bootstrap" >/dev/null; then
    echo "✅ Tomcat running fine."
  else
    echo "๐Ÿšจ Tomcat stopped! Restarting..."
    /opt/tomcat/bin/startup.sh || echo "❌ Failed to restart Tomcat."
  fi
  sleep 10
done
๐Ÿ’ก Use pgrep + startup.sh for continuous checks. If restart fails, check logs in /opt/tomcat/logs/catalina.out.

๐ŸŒ Example 7: Auto-Restart NGINX if Down

#!/bin/bash
while true
do
  systemctl is-active nginx >/dev/null 2>&1
  if [ $? -ne 0 ]; then
    echo "๐Ÿšจ NGINX down! Restarting..."
    systemctl restart nginx || echo "⚠️ Failed to restart NGINX!"
  else
    echo "๐ŸŒ NGINX OK"
  fi
  sleep 15
done
⚙️ If systemctl restart fails, check journal logs: journalctl -u nginx -xe

3️⃣ The until Loop

The until loop runs repeatedly until a condition becomes true. Best used to wait for Jenkins, DB, or a service to be ready.

๐Ÿงฉ Example 8: Wait for Jenkins to Start

#!/bin/bash
until curl -s http://localhost:8080 >/dev/null
do
  echo "Waiting for Jenkins to start..."
  sleep 5
done
echo "✅ Jenkins is running!"
๐Ÿ•’ If it loops forever, verify Jenkins logs with tail -f /var/log/jenkins/jenkins.log.

๐Ÿ’พ Example 9: Wait for Database Connection

#!/bin/bash
until nc -zv dbserver 3306 >/dev/null 2>&1
do
  echo "⏳ Waiting for DB..."
  sleep 5
done
echo "✅ Database reachable!"
If connection keeps failing, check DB firewall or credentials in .env files.

๐Ÿงฑ Example 10: Wait Until Backup Completes

#!/bin/bash
until [ -f /opt/backups/backup_done.flag ]
do
  echo "Backup still running..."
  sleep 10
done
echo "✅ Backup completed successfully!"

๐Ÿง  Debugging & Error Handling Tips

  • Use set -x at top to debug each executed line.
  • Use || echo "Command failed" for inline failure tracking.
  • Use continue inside loops to skip failed items safely.
  • Use exit 1 if you want to terminate on critical errors.
  • Always log outputs: command >> /var/log/script.log 2>&1

๐Ÿ Summary

  • for loop – Repeats tasks for lists (servers, files).
  • while loop – Keeps running while condition is true.
  • until loop – Keeps running until condition becomes true.
  • Error Handling – Use set -e, $?, ||, and continue for reliability.

๐Ÿ”ฅ Loops make your middleware automation resilient — whether it’s Tomcat restarts, WebSphere cleanups, or NGINX monitoring. Next up → Part 5: Shell Functions – Make Your Scripts Modular & Reusable ⚙️

No comments:

Post a Comment