Menu

Saturday, 1 November 2025

⚙️ Shell Scripting for Beginners – Part 5: Functions in Shell (Reusable Scripts)

  • Functions let you organize and reuse code in your shell scripts like a Middleware and DevOps engineer.
  • Instead of repeating logic for Tomcat restarts or Jenkins backups, define it once — then call it from anywhere.
  • We'll also explore how to handle errors gracefully inside functions.

πŸ“‘ Table of Contents


πŸ’‘ What is a Function?

A function groups commands under one name so you can call them repeatedly. In Middleware automation, you can define restart, deploy, or monitor tasks as reusable functions.


🧩 Function Syntax

function_name() {
   commands
}
# OR
function function_name {
   commands
}

🎯 Example 1: Basic Function

#!/bin/bash
say_hello() {
  echo "Hello from MiddlewareBox!"
}
say_hello
πŸ’¬ Output:
Hello from MiddlewareBox!

🧠 Example 2: Function with Parameters

#!/bin/bash
greet_user() {
  echo "Welcome $1! You are working on the $2 environment."
}
greet_user Pradeep DevOps
πŸ’¬ Output:
Welcome Pradeep! You are working on the DevOps environment.

πŸ“¦ Example 3: Function with Return Value

#!/bin/bash
add_numbers() {
  sum=$(( $1 + $2 ))
  echo $sum
}
result=$(add_numbers 25 30)
echo "The total is: $result"
πŸ’¬ Output:
The total is: 55

🧰 Example 4: Restart Tomcat (with error handling)

#!/bin/bash
restart_tomcat() {
  echo "Stopping Tomcat..."
  /opt/tomcat/bin/shutdown.sh || { echo "❌ Failed to stop Tomcat"; return 1; }
  sleep 3
  echo "Starting Tomcat..."
  /opt/tomcat/bin/startup.sh || { echo "❌ Failed to start Tomcat"; return 2; }
  echo "✅ Tomcat restarted successfully!"
}
restart_tomcat
πŸ’¬ Output:
Stopping Tomcat...
Starting Tomcat...
✅ Tomcat restarted successfully!
If Tomcat fails to start, check /opt/tomcat/logs/catalina.out.

πŸ’Ύ Example 5: Jenkins Backup Function (with error handling)

#!/bin/bash
backup_jenkins() {
  backup_dir="/var/jenkins_home/backup"
  mkdir -p $backup_dir || { echo "❌ Failed to create backup directory"; return 1; }
  tar -czf $backup_dir/jenkins_$(date +%F).tar.gz /var/jenkins_home || { echo "❌ Backup failed"; return 2; }
  echo "✅ Backup saved in $backup_dir"
}
backup_jenkins
If backup fails, ensure enough disk space and Jenkins home path is correct.

🧹 Example 6: WebSphere Log Cleanup

#!/bin/bash
cleanup_was_logs() {
  log_path="/opt/IBM/WebSphere/AppServer/logs"
  echo "Cleaning logs in $log_path"
  find $log_path -name "*.log" -type f -mtime +7 -exec rm -f {} \; || echo "⚠️ Cleanup error occurred"
  echo "🧹 Old WebSphere logs removed successfully."
}
cleanup_was_logs
If permissions fail, run with sudo or check AppServer/logs ownership.

🧠 Example 7: Database Health Check

#!/bin/bash
check_db() {
  if nc -zv dbserver 3306 >/dev/null 2>&1; then
    echo "✅ Database reachable"
  else
    echo "🚨 Database not reachable!"
    return 1
  fi
}
check_db || echo "⚙️ Please verify DB server or firewall."

πŸš€ Example 8: Modular CI/CD Wrapper

#!/bin/bash
deploy_app() {
  echo "Building app..."
  mvn clean package || { echo "❌ Build failed"; return 1; }
  echo "Deploying WAR..."
  scp target/app.war prod:/opt/tomcat/webapps/ || { echo "❌ Deploy failed"; return 2; }
  ssh prod "systemctl restart tomcat"
  echo "✅ Deployment complete!"
}
deploy_app
If deploy fails, verify SSH connectivity and WAR path.

🏁 Summary

  • Functions make scripts modular, reusable, and easier to maintain.
  • Handle errors using return and conditional checks.
  • Great for DevOps: automate Jenkins, Tomcat, WebSphere, and CI/CD pipelines.
  • Combine with loops and conditionals from previous lessons for full automation.

No comments:

Post a Comment