Automate System Monitoring on Ubuntu with Bash Script

Automate System Monitoring on Ubuntu with Bash Script
09/19/2025 •

📌 Introduction to the System Monitoring Script

In modern IT environments, ensuring system stability, performance, and resource availability is critical. While enterprise monitoring tools like Nagios, Zabbix, and Prometheus offer robust solutions, there are many scenarios—especially on lightweight servers, personal machines, or isolated environments—where a simple, efficient, and script-based solution is more appropriate.

This Bash-based system monitoring script provides a lightweight and automated way to track the health and resource usage of a Linux system. It collects essential metrics such as CPU usage, memory consumption, disk space, and running processes, and logs them into daily timestamped files under /var/log/. By running periodically (e.g., via cron), it allows system administrators and developers to maintain a historical record of system performance without relying on external software or agents.

Automate System Monitoring on Ubuntu with Bash Script

The script is easy to configure, extend, and deploy, making it an ideal choice for quick health checks, resource audits, and troubleshooting system performance in a wide range of environments—from development systems to production servers.

Guide for setting up a system monitoring Bash script on Ubuntu Linux that:

  • Collects CPU, memory, disk usage, uptime, and active jobs
  • Runs automatically every 30 minutes
  • Creates a new log file daily with the format sys_monitor_YYYY-MM-DD.log
  • Optionally deletes old logs after 30 days

📝 Purpose of This Solution

This setup helps automate the process of collecting system resource usage statistics on a Linux system. It provides:

  • Continuous tracking of system health
  • Daily archived logs
  • Historical data for performance analysis
  • Minimal resource footprint

It is especially useful for:

  • System administrators
  • DevOps engineers
  • Self-hosted server users
  • Cloud VPS monitoring

🧰 What the Script Does

Every 30 minutes, the Bash script performs the following actions:

TaskCommand UsedPurpose
Adds a timestampdate ‘+%Y-%m-%d %H:%M:%S’Logs the exact time of each entry
Checks system uptimeuptimeShows how long the system has been running and its load average
Lists top CPU-consuming processes`ps -eo pid,ppid,cmd,%cpu –sort=-%cpuhead -n 6`
Displays memory usagefree -hProvides readable output of used and available RAM
Lists top memory-hungry processes`ps -eo pid,ppid,cmd,%mem –sort=-%memhead -n 6`
Reports disk usagedf -hDisplays disk utilization of mounted partitions
Shows active jobs (running state)`ps -eo pid,stat,cmdgrep ‘ R’`
Stores data in daily logssys_monitor_YYYY-MM-DD.logSegregates logs by day for easy analysis
Deletes logs older than 30 daysfind /var/log/ -name “sys_monitor_*.log” -mtime +30Prevents log directory from filling up

🛠️ Step-by-Step Setup Guide


🔹 Step 1: Create the Bash Script

Open a terminal and run:

      nano /usr/local/bin/sys_monitor.sh
    

Paste the following script inside:

      #!/bin/bash

# ================================
# System Monitoring Script
# Logs system stats into daily log files in /var/log/
# ================================

DATE=$(date '+%Y-%m-%d')
TIME=$(date '+%Y-%m-%d %H:%M:%S')
LOGFILE="/var/log/sys_monitor_${DATE}.log"

# Create log file with header if not exists
if [ ! -f "$LOGFILE" ]; then
    echo "===== System Monitoring Log for $DATE =====" > "$LOGFILE"
fi

{
    echo ""
    echo "===== $TIME ====="

    # Uptime
    echo ""
    echo "--- UPTIME ---"
    uptime

    # CPU Usage (Top 5)
    echo ""
    echo "--- CPU USAGE (Top 5 by %CPU) ---"
    ps -eo pid,ppid,cmd,%cpu --sort=-%cpu | head -n 6

    # Total CPU Usage
    echo ""
    echo "--- TOTAL CPU USAGE ---"
    top -bn1 | grep "^%Cpu" | awk '{usage = 100 - $8; printf "Total CPU Usage: %.2f%%n", usage}'

    # Memory Usage
    echo ""
    echo "--- MEMORY USAGE ---"
    free -h

    # Total Memory Usage
    echo ""
    echo "--- TOTAL MEMORY USAGE ---"
    free | awk '/Mem:/ {
        total=$2; used=$3;
        printf "Used: %.2f%% (%d MB of %d MB)n", used/total*100, used/1024, total/1024
    }'

    # Top 5 Memory-Hungry Processes
    echo ""
    echo "--- TOP 5 MEMORY HUNGRY PROCESSES ---"
    ps -eo pid,ppid,cmd,%mem --sort=-%mem | head -n 6

    # Disk Usage
    echo ""
    echo "--- DISK USAGE ---"
    df -h

    # Total Disk Usage
    echo ""
    echo "--- TOTAL DISK USAGE SUMMARY ---"
    df --total -h | awk '/total/ {print "Total Used: "$3" / "$2" ("$5" used)"}'

    # Active Running Jobs
    echo ""
    echo "--- ACTIVE JOBS (Running State) ---"
    ps -eo pid,stat,cmd --sort=stat | awk '$2 ~ /R/'

    # Separator
    echo ""
    echo "----------------------------------"

} >> "$LOGFILE"

# Cleanup logs older than 30 days
find /var/log/ -name "sys_monitor_*.log" -type f -mtime +30 -exec rm -f {} ;


    

🔹 Step 2: Make the Script Executable

      sudo chmod +x /usr/local/bin/sys_monitor.sh
    

🔹 Step 3: testing the script

      sh /usr/local/bin/sys_monitor.sh
    

🔹 Step 4: Setup Log Directory Permissions (if needed)

Ensure you can write to /var/log/:

      sudo chown $USER:$USER /var/log/sys_monitor_*.log
    

Alternatively, you can change the script’s log path to a user directory like ~/logs/.

How to check the logs files

      ls -l /var/log | grep sys_monitor_
    

🔹 Step 5: Schedule the Script Every 30 Minutes (via Cron)

Edit your crontab:

      crontab -e
    

Add this line at the bottom:

      */30 * * * * /usr/local/bin/sys_monitor.sh
    

This will run the script every 30 minutes, day and night.


🔹 Step 6: Check If Cron Is Working

Ensure cron is active:

      sudo systemctl status cron
    

Start it if inactive:

      sudo systemctl start cron
    
      sudo systemctl enable cron
    

📂 Log File Output Example

File path: /var/log/sys_monitor_2025-07-23.log


🧠 Why This Is Useful (Use Cases)

Use CaseBenefit
🛠️ System AdminsRegular performance monitoring without manual effort
📊 Data CollectionLong-term logging for performance audits
🧪 DebuggingHelps pinpoint resource spikes or application failures
🚨 Future AutomationCan add alerts for high CPU, memory, or disk usage

Result

After a few days, your /var/log/ will have:

Each file contains entries every 30 minutes for that day. Rotating weekly is now automated through daily logs + optional cleanup after 30 days.



🗂️ File and Folder Structure

PathDescription
/usr/local/bin/sys_monitor.shThe Bash script to be run
/var/log/sys_monitor_YYYY-MM-DD.logDaily log file where all outputs are saved
crontab -e entryCron job to schedule script execution every 30 minutes

🧾 Daily Log Example

Each log file contains multiple timestamped entries like:


⏲️ Automation via Cron

By adding the script to crontab, the system automatically runs it every 30 minutes — no manual intervention required.

Crontab Entry:

This enables:

  • Consistent and regular data collection
  • Fully unattended operation
  • Logs available for audit or troubleshooting

📉 Why Rotate Logs Daily?

  • Keeps log files manageable in size
  • Easier to troubleshoot issues on specific dates
  • Facilitates weekly/monthly analysis
  • Prepares data for archiving or deletion

Optional Cleanup Feature:

      find /var/log/ -name "sys_monitor_*.log" -type f -mtime +30 -exec rm {} ;
    

This deletes logs older than 30 days to conserve disk space.


🔐 Security and Access

  • The script writes to /var/log/, so it must have sufficient write permissions.
  • You can either:
    • Run the script via cron as root, or
    • Change the log path to a user directory like ~/syslogs/

🚀 Advantages of This Setup

FeatureBenefit
🕒 30-minute intervalBalances detail and efficiency
📁 Daily log filesEasy to manage and analyze
🔁 Auto-cleanupSaves storage space
🧩 Modular scriptEasy to extend with alerts, graphs, etc.
⚙️ Fully automaticNo manual actions needed after setup
🛡️ LightweightMinimal performance overhead

Summary of the Script:

This Bash system monitoring script collects real-time system statistics and saves them into daily log files in the /var/log/ directory. It provides detailed insights into system health including CPU, memory, disk usage, and active jobs.


🔍 Features:

  1. Timestamped Logs:
    Each log entry includes a timestamp, enabling easy tracking of system changes over time.
  2. CPU Metrics:
    • Top 5 processes by CPU usage.
    • Total CPU usage percentage calculated from idle time.
  3. Memory Metrics:
    • Human-readable memory usage (free -h).
    • Total memory used in % and MB.
  4. Disk Metrics:
    • Per-mount disk usage using df -h.
    • Total disk usage summary (aggregated size, used space, percentage).
  5. Active Running Processes:
    • Lists processes currently in Running (R) state.
  6. Automatic Log Management:
    • Deletes logs older than 30 days to prevent disk bloat.

🛠️ Use Cases:

  • System admins managing servers with limited monitoring tools.
  • Root-cause analysis after a performance degradation.
  • Long-term performance trend analysis.
  • Lightweight alternative to tools like Nagios, Zabbix, or Prometheus for small environments.

Useful Links

https://ubuntu.com

https://gcc.gnu.org

https://sanchitgurukul.com/basic-networking

https://sanchitgurukul.com/network-security

https://sanchitgurukul.com/how-to-articles/


Automate System Monitoring on Ubuntu with Bash Script

This article provided insights on the topic. For latest updates and detailed guides, stay connected with Sanchit Gurukul.

Disclaimer: This article may contain information that was accurate at the time of writing but could be outdated now. Please verify details with the latest vendor advisories or contact us at admin@sanchitgurukul.com.

Discover more from

Subscribe now to keep reading and get access to the full archive.

Continue reading