Blog 14 From Basics to Pro: Functions, Logs & Loops in Shell Scripting

Functions, Colors, Logs & Loops in Shell Scripting

Functions, Colors, Logs & Loops in Shell Scripting

Welcome back to our shell scripting series 🚀 In the last blog, we covered variables, conditions, and datatypes. Today, let’s step into some powerful concepts: Functions, Colors, Logs, and Loops. These are the real game-changers when building scripts for automation.


1️⃣ Functions – Reuse Your Code

A function is like a shortcut. Instead of repeating the same lines, wrap them in a function and call it anytime.

FUNC_NAME() {
   # code here
}

FUNC_NAME   # calling function
  

2️⃣ Passing Arguments

You can pass inputs to your function. Inside the function, $1 means the first argument, $2 the second, and so on.

FUNC_NAME input1 input2

FUNC_NAME() {
   echo "First arg: $1"
   echo "Second arg: $2"
}
  

3️⃣ Why Use Functions?

  • Follow DRY → Don’t Repeat Yourself
  • Keep scripts clean & structured
  • Debugging becomes easier

4️⃣ Adding Colors to Output

Colors make scripts friendly to read and errors easy to spot.

  • Green → Success (32)
  • Red → Failure (31)
  • Yellow → Already Installed (33)
echo -e "\e[32mInstallation Successful\e[0m"
echo -e "\e[31mInstallation Failed\e[0m"
echo -e "\e[33mAlready Installed\e[0m"
  

5️⃣ Logging with Redirectors

Every professional script should log its output. That’s how you track what happened.

  • > → output redirection
  • < → input redirection
  • 1 → success logs
  • 2 → error logs
  • & → combine both

Example log file naming: /var/logs/13-logs-01-01-2025.log

6️⃣ Why Logs?

  • Helps in debugging errors
  • Keeps a history of script runs
  • Gives visibility into automation

7️⃣ Loops – Automate Repetitive Tasks

Loops save you from typing the same command again and again.

for i in {0..10}; do
   echo $i
done
  

8️⃣ C-Style Loops

for((i=0; i<100; i++)); do
   echo $i
done
  

9️⃣ Practical Example – Package Installer

Let’s install multiple packages (git, mysql, gcc, nginx) in one go using a loop.

#!/bin/bash

for package in git mysql gcc nginx
do
   echo "Installing $package..."
   yum install -y $package &>> install.log
done
  

🔟 Why Loops?

  • Handle multiple tasks with fewer lines
  • Ensure consistency
  • Perfect for bulk operations

1️⃣1️⃣ Bringing It All Together

A production-ready script usually has:

  • Functions → for reusability
  • Colors → for clarity
  • Logs → for tracking
  • Loops → for automation

1️⃣2️⃣ Final Takeaway

Functions, colors, logs, and loops transform basic scripts into professional automation tools. Master these concepts, and you’ll not just write scripts — you’ll build systems 🔥

👉 Stay tuned for the next blog in this series where we’ll dive deeper into real-world use cases. #DevOps #ShellScripting #Automation


© Kalyan – DevSecOps Journey

Comments

Popular Posts