📌 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.

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:
| Task | Command Used | Purpose |
| Adds a timestamp | date ‘+%Y-%m-%d %H:%M:%S’ | Logs the exact time of each entry |
| Checks system uptime | uptime | Shows how long the system has been running and its load average |
| Lists top CPU-consuming processes | `ps -eo pid,ppid,cmd,%cpu –sort=-%cpu | head -n 6` |
| Displays memory usage | free -h | Provides readable output of used and available RAM |
| Lists top memory-hungry processes | `ps -eo pid,ppid,cmd,%mem –sort=-%mem | head -n 6` |
| Reports disk usage | df -h | Displays disk utilization of mounted partitions |
| Shows active jobs (running state) | `ps -eo pid,stat,cmd | grep ‘ R’` |
| Stores data in daily logs | sys_monitor_YYYY-MM-DD.log | Segregates logs by day for easy analysis |
| Deletes logs older than 30 days | find /var/log/ -name “sys_monitor_*.log” -mtime +30 | Prevents 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
===== System Monitoring Log for 2025-08-04 =====
===== 2025-08-04 05:13:03 =====
--- UPTIME ---
05:13:03 up 131 days, 22:08, 1 user, load average: 0.06, 0.02, 0.00
--- CPU USAGE (Top 5 by %CPU) ---
PID PPID CMD %CPU
622 621 falcon-sensor 0.1
22927 1 /usr/bin/containerd 0.1
1 0 /sbin/init maybe-ubiquity 0.0
2 0 [kthreadd] 0.0
3 2 [rcu_gp] 0.0
--- TOTAL CPU USAGE ---
Total CPU Usage: 14.30%
--- MEMORY USAGE ---
total used free shared buff/cache available
Mem: 3.8Gi 290Mi 403Mi 1.0Mi 3.1Gi 3.3Gi
Swap: 3.8Gi 0.0Ki 3.8Gi
--- TOTAL MEMORY USAGE ---
Used: 7.42% (290 MB of 3919 MB)
--- TOP 5 MEMORY HUNGRY PROCESSES ---
PID PPID CMD %MEM
4372 1 /usr/bin/dockerd -H fd:// - 1.8
22927 1 /usr/bin/containerd 1.1
286387 1 /usr/lib/snapd/snapd 0.9
622 621 falcon-sensor 0.6
4311 1 /usr/bin/python3 /usr/share 0.5
--- DISK USAGE ---
Filesystem Size Used Avail Use% Mounted on
udev 1.9G 0 1.9G 0% /dev
tmpfs 392M 1.3M 391M 1% /run
/dev/mapper/ubuntu--vg-ubuntu--lv 20G 14G 5.5G 71% /
tmpfs 2.0G 0 2.0G 0% /dev/shm
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 2.0G 0 2.0G 0% /sys/fs/cgroup
/dev/loop4 92M 92M 0 100% /snap/lxd/29619
/dev/loop7 92M 92M 0 100% /snap/lxd/32662
/dev/sda2 974M 222M 685M 25% /boot
/dev/loop2 64M 64M 0 100% /snap/core20/2582
/dev/loop0 64M 64M 0 100% /snap/core20/2599
/dev/loop5 51M 51M 0 100% /snap/snapd/24718
/dev/loop6 50M 50M 0 100% /snap/snapd/24792
/dev/loop1 56M 56M 0 100% /snap/core18/2923
/dev/loop3 56M 56M 0 100% /snap/core18/2934
tmpfs 392M 0 392M 0% /run/user/0
--- TOTAL DISK USAGE SUMMARY ---
Total Used: 14G / 28G (53% used)
--- ACTIVE JOBS (Running State) ---
339047 R+ ps -eo pid,stat,cmd --sort=stat
----------------------------------
🧠 Why This Is Useful (Use Cases)
| Use Case | Benefit |
| 🛠️ System Admins | Regular performance monitoring without manual effort |
| 📊 Data Collection | Long-term logging for performance audits |
| 🧪 Debugging | Helps pinpoint resource spikes or application failures |
| 🚨 Future Automation | Can add alerts for high CPU, memory, or disk usage |
Result
After a few days, your /var/log/ will have:
/var/log/sys_monitor_2025-07-23.log
/var/log/sys_monitor_2025-07-24.log
/var/log/sys_monitor_2025-07-25.log
…
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
| Path | Description |
| /usr/local/bin/sys_monitor.sh | The Bash script to be run |
| /var/log/sys_monitor_YYYY-MM-DD.log | Daily log file where all outputs are saved |
| crontab -e entry | Cron job to schedule script execution every 30 minutes |
🧾 Daily Log Example
Each log file contains multiple timestamped entries like:
===== System Monitoring Log for 2025-08-04 =====
===== 2025-08-04 05:13:03 =====
--- UPTIME ---
05:13:03 up 131 days, 22:08, 1 user, load average: 0.06, 0.02, 0.00
--- CPU USAGE (Top 5 by %CPU) ---
PID PPID CMD %CPU
622 621 falcon-sensor 0.1
22927 1 /usr/bin/containerd 0.1
1 0 /sbin/init maybe-ubiquity 0.0
2 0 [kthreadd] 0.0
3 2 [rcu_gp] 0.0
--- TOTAL CPU USAGE ---
Total CPU Usage: 14.30%
--- MEMORY USAGE ---
total used free shared buff/cache available
Mem: 3.8Gi 290Mi 403Mi 1.0Mi 3.1Gi 3.3Gi
Swap: 3.8Gi 0.0Ki 3.8Gi
--- TOTAL MEMORY USAGE ---
Used: 7.42% (290 MB of 3919 MB)
--- TOP 5 MEMORY HUNGRY PROCESSES ---
PID PPID CMD %MEM
4372 1 /usr/bin/dockerd -H fd:// - 1.8
22927 1 /usr/bin/containerd 1.1
286387 1 /usr/lib/snapd/snapd 0.9
622 621 falcon-sensor 0.6
4311 1 /usr/bin/python3 /usr/share 0.5
--- DISK USAGE ---
Filesystem Size Used Avail Use% Mounted on
udev 1.9G 0 1.9G 0% /dev
tmpfs 392M 1.3M 391M 1% /run
/dev/mapper/ubuntu--vg-ubuntu--lv 20G 14G 5.5G 71% /
tmpfs 2.0G 0 2.0G 0% /dev/shm
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 2.0G 0 2.0G 0% /sys/fs/cgroup
/dev/loop4 92M 92M 0 100% /snap/lxd/29619
/dev/loop7 92M 92M 0 100% /snap/lxd/32662
/dev/sda2 974M 222M 685M 25% /boot
/dev/loop2 64M 64M 0 100% /snap/core20/2582
/dev/loop0 64M 64M 0 100% /snap/core20/2599
/dev/loop5 51M 51M 0 100% /snap/snapd/24718
/dev/loop6 50M 50M 0 100% /snap/snapd/24792
/dev/loop1 56M 56M 0 100% /snap/core18/2923
/dev/loop3 56M 56M 0 100% /snap/core18/2934
tmpfs 392M 0 392M 0% /run/user/0
--- TOTAL DISK USAGE SUMMARY ---
Total Used: 14G / 28G (53% used)
--- ACTIVE JOBS (Running State) ---
339047 R+ ps -eo pid,stat,cmd --sort=stat
----------------------------------
⏲️ Automation via Cron
By adding the script to crontab, the system automatically runs it every 30 minutes — no manual intervention required.
Crontab Entry:
*/30 * * * * /usr/local/bin/sys_monitor.sh
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
| Feature | Benefit |
| 🕒 30-minute interval | Balances detail and efficiency |
| 📁 Daily log files | Easy to manage and analyze |
| 🔁 Auto-cleanup | Saves storage space |
| 🧩 Modular script | Easy to extend with alerts, graphs, etc. |
| ⚙️ Fully automatic | No manual actions needed after setup |
| 🛡️ Lightweight | Minimal 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:
- Timestamped Logs:
Each log entry includes a timestamp, enabling easy tracking of system changes over time. - CPU Metrics:
- Top 5 processes by CPU usage.
- Total CPU usage percentage calculated from idle time.
- Memory Metrics:
- Human-readable memory usage (free -h).
- Total memory used in % and MB.
- Disk Metrics:
- Per-mount disk usage using df -h.
- Total disk usage summary (aggregated size, used space, percentage).
- Active Running Processes:
- Lists processes currently in Running (R) state.
- 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://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.
