Keeping an eye on your system’s performance is crucial for maintaining a healthy and efficient environment. This Bash script monitors CPU and memory usage, logging the information to a file for later analysis.

Step-by-Step Guide:

1. Define the Log File: Specify the location where the log file will be stored.

LOG_FILE="/var/log/sys_monitor.log"


2. Capture System Resource Usage: Use top to get CPU usage and free to get memory usage.

DATE=$(date +"%Y-%m-%d %H:%M:%S")

CPU_USAGE=$(top -bn1 | grep “Cpu(s)” | sed “s/.*, *\([0-9.]*\)%* id.*/\1/” | awk ‘{print 100 – $1″%”}’)

MEM_USAGE=$(free -m | awk ‘NR==2{printf “Memory Usage: %s/%sMB (%.2f%%)\n”, $3, $2, $3*100/$2 }’)


3. Log the Information: Append the collected data to the log file.

echo "$DATE - CPU Usage: $CPU_USAGE, $MEM_USAGE" >> $LOG_FILE


Complete Script:

#!/bin/bash

# Log file
LOG_FILE=“/var/log/sys_monitor.log”

# Capture system resource usage
DATE=$(date +“%Y-%m-%d %H:%M:%S”)
CPU_USAGE=$(top -bn1 | grep “Cpu(s)” | sed “s/.*, *\([0-9.]*\)%* id.*/\1/” | awk ‘{print 100 – $1″%”}’)
MEM_USAGE=$(free -m | awk ‘NR==2{printf “Memory Usage: %s/%sMB (%.2f%%)\n”, $3, $2, $3*100/$2 }’)

# Log the information
echo $DATE – CPU Usage: $CPU_USAGE, $MEM_USAGE >> $LOG_FILE

Usage:

  • Save the script and run it manually or set up a cron job to execute it periodically.

This simple script helps you keep track of your system’s performance over time, making it easier to identify trends and potential issues.

Looking for a more functional alternative? – check on sar tool.