Menu

Saturday, 1 November 2025

πŸ’‘Shell Scripting for Beginners – Part 8: Debugging & Logging

  • By now, your scripts deploy apps, manage servers, and clean logs.
  • But what happens when things go wrong?
  • Welcome to Debugging & Logging, where we make your scripts smarter and traceable like a pro DevOps engineer! πŸ•΅️‍♂️

πŸ“‘ Table of Contents


🐞 1️⃣ Debugging with set -x

set -x shows every command the script executes — perfect for troubleshooting silent errors.

#!/bin/bash
set -x  # enable debugging
echo "Starting deployment..."
mkdir /opt/app/deploy
cp /tmp/app.war /opt/app/deploy/
set +x  # disable debugging
echo "Deployment finished!"
πŸ’¬ Output:
+ echo "Starting deployment..."
Starting deployment...
+ mkdir /opt/app/deploy
+ cp /tmp/app.war /opt/app/deploy/
+ echo "Deployment finished!"
Deployment finished!
πŸ’‘ Use bash -x script.sh to debug a script without editing it.

πŸͺ€ 2️⃣ Using trap to Handle Failures

The trap command catches unexpected exits (Ctrl+C, errors) and executes custom recovery code. Perfect for cleanup or service restarts.

#!/bin/bash
trap 'echo "⚠️ Script interrupted! Cleaning up..."; rm -f /tmp/tempfile' EXIT
echo "Creating temporary file..."
touch /tmp/tempfile
echo "Simulating work..."
sleep 3
exit 1  # simulate failure
πŸ’¬ Output:
Creating temporary file...
Simulating work...
⚠️ Script interrupted! Cleaning up...
πŸ’‘ Always trap EXIT or ERR to prevent orphan temp files or hanging processes.

πŸšͺ 3️⃣ Exit Codes & Error Messages

Every command returns an exit code — 0 means success, non-zero means failure.

#!/bin/bash
cp /tmp/app.war /opt/app/deploy/
if [ $? -ne 0 ]; then
  echo "❌ Copy failed! Check file path or permissions."
  exit 1
else
  echo "✅ Copy successful!"
fi
πŸ’¬ Output:
❌ Copy failed! Check file path or permissions.
or
✅ Copy successful!
Use echo $? after any command to view its exit code.

🧾 4️⃣ Logging with Syslog & Custom Files

Example 1: Using logger Command

#!/bin/bash
logger "Starting Middleware backup..."
tar -czf /tmp/backup.tar.gz /opt/middleware/ || logger "Backup failed!"
logger "Middleware backup completed!"
πŸ’¬ Syslog Output (in /var/log/syslog):
Nov 1 02:15:00 server logger: Starting Middleware backup...
Nov 1 02:15:03 server logger: Middleware backup completed!

Example 2: Redirecting Logs to a File

#!/bin/bash
exec >> /opt/logs/deploy.log 2>&1
echo "[$(date)] Starting deployment..."
echo "[$(date)] Copying WAR..."
cp /tmp/app.war /opt/tomcat/webapps/
echo "[$(date)] Deployment done ✅"
πŸ’¬ deploy.log Content:
[Sat Nov 1 02:20:00 2025] Starting deployment...
[Sat Nov 1 02:20:01 2025] Copying WAR...
[Sat Nov 1 02:20:02 2025] Deployment done ✅

⚙️ 5️⃣ Real Middleware & DevOps Examples

Example 1: Jenkins Job Failure Recovery

#!/bin/bash
set -e
trap 'echo "🚨 Jenkins build failed, restarting service..."; systemctl restart jenkins' ERR
curl -s -X POST "http://localhost:8080/job/myjob/build" || false
echo "✅ Jenkins job triggered successfully!"
πŸ’¬ Output:
🚨 Jenkins build failed, restarting service...
✅ Jenkins job triggered successfully!

Example 2: Tomcat Log Watcher with Debug Info

#!/bin/bash
set -x
tail -Fn0 /opt/tomcat/logs/catalina.out | \
while read line; do
  echo "$line" | grep "ERROR" &>/dev/null && echo "πŸ”₯ Found error: $line" >> /opt/logs/tomcat_error.log
done
πŸ’¬ Output:
[DEBUG] + grep "ERROR" catalina.out
πŸ”₯ Found error: Database connection timeout

Example 3: NGINX Health Check with Logging

#!/bin/bash
while true; do
  if ! systemctl is-active nginx >/dev/null; then
    echo "$(date): 🚨 NGINX is down, restarting..." >> /var/log/nginx_monitor.log
    systemctl restart nginx
  fi
  sleep 10
done
πŸ’¬ Log Output:
Sat Nov 1 03:00:00 2025: 🚨 NGINX is down, restarting...

🏁 Summary

  • set -x → Debug command execution flow.
  • trap → Catch exits & clean up automatically.
  • exit codes → Detect and handle failures gracefully.
  • logger → Send messages to syslog or custom logs.
  • πŸ’‘ Always include logging in production-ready scripts for audit and rollback.

No comments:

Post a Comment