DEV Community

Cover image for BashBlaze Day 4: Building a System Monitoring Script with Bash
Muhammad Hanzala Ali
Muhammad Hanzala Ali

Posted on

BashBlaze Day 4: Building a System Monitoring Script with Bash

Welcome to Day 4 of the BashBlaze - 7 Days of Bash Scripting Challenge! Today, we’re tackling an essential skill in the DevOps toolkit: creating a script to monitor system metrics. This task will help you build a deeper understanding of Bash scripting, system monitoring, and user interaction. Ready to take your scripting game up a notch? Let’s dive in!

The Goal: A Robust Monitoring Script

The mission for today’s challenge is to develop a Bash script that:

  • Monitors CPU usage, memory usage, and disk space.
  • Provides a simple, interactive menu.
  • Continuously displays metrics with user-defined intervals.
  • Monitors the status of specific services like Nginx.
  • Handles errors gracefully.

Task Breakdown

Task 1: Basic Metrics Monitoring

Start by writing a basic script to display CPU, memory, and disk space information:

#!/bin/bash

# Function to display system metrics
show_metrics() {
    echo "\n---- System Metrics ----"
    echo "CPU Usage: $(top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}')%"
    echo "Memory Usage: $(free -m | awk '/Mem:/ {printf("%d/%dMB (%.2f%%)", $3, $2, $3*100/$2)}')"
    echo "Disk Space: $(df -h / | awk 'NR==2 {print $5}')"
    echo "\nPress Enter to continue..."
    read
}
Enter fullscreen mode Exit fullscreen mode

Task 2: User-Friendly Interface

Enhance the script by creating a menu that allows users to select different options:

while true; do
    clear
    echo "---- Monitoring Metrics Script ----"
    echo "1. View System Metrics"
    echo "2. Monitor a Specific Service"
    echo "3. Exit"
    read -p "Choose an option (1-3): " choice

    case $choice in
        1) show_metrics;;
        2) monitor_service;;
        3) echo "Exiting..."; break;;
        *) echo "Invalid option. Please try again."; sleep 2;;
    esac
done
Enter fullscreen mode Exit fullscreen mode

Task 3: Continuous Monitoring with Sleep

To enable continuous monitoring, add a loop with a sleep mechanism that pauses between each refresh:

read -p "Enter sleep interval in seconds: " sleep_interval
while true; do
    show_metrics
    sleep $sleep_interval
done
Enter fullscreen mode Exit fullscreen mode

Task 4: Monitor Specific Services
Expand the script to check the status of services such as Nginx:

monitor_service() {
    read -p "Enter the service name to monitor: " service
    if systemctl is-active --quiet $service; then
        echo "$service is running."
    else
        echo "$service is not running. Do you want to start it? (Y/N)"
        read start_choice
        if [[ $start_choice == "Y" || $start_choice == "y" ]]; then
            sudo systemctl start $service
            echo "$service started."
        else
            echo "$service was not started."
        fi
    fi
    echo "\nPress Enter to continue..."
    read
}
Enter fullscreen mode Exit fullscreen mode

Task 5: Allow User to Choose Different Services

Add flexibility by letting users input any service they wish to monitor.

Task 6: Error Handling

Ensure the script includes error handling to manage command failures and invalid inputs. Use conditional checks and meaningful error messages to enhance user experience.

Conclusion

This Day 4 challenge empowers you with the knowledge to create a monitoring script that’s both practical and versatile. With user-friendly features and a touch of DevOps flair, this project is an excellent addition to your Bash scripting portfolio.

What creative name did you give your script? Share your progress and feedback in the comments!

Top comments (0)