Bash Programming

Bash Script: System Resource Monitor Script


#!/bin/bash

# Function to get current date and time
get_date() {
date +"%Y-%m-%d %H:%M:%S"
}

# Function to monitor CPU, Memory, and Disk usage
monitor_resources() {
while true; do
# Get current date and time
current_date=$(get_date)

# Get CPU usage
cpu_usage=$(top -bn1 | grep "Cpu(s)" | \
sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \
awk '{print 100 - $1}')

# Get Memory usage
memory_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')

# Get Disk usage
disk_usage=$(df -h / | awk '$NF=="/"{printf "%s", $5}')

# Log data to file
echo "$current_date - CPU: $cpu_usage%, Memory: $memory_usage%, Disk: $disk_usage" >> resource_monitor.log

# Sleep for 5 seconds
sleep 5
done
}

# Start monitoring resources
monitor_resources

This Bash script monitors system resources such as CPU, memory, and disk usage. It includes functions to get the current date and time, as well as to monitor the resources continuously. The script uses commands like `top`, `free`, and `df` to gather CPU, memory, and disk usage data respectively. The data is then logged to a file named `resource_monitor.log` with timestamps for later analysis.

This script can be run in the background to continuously monitor system resources and log the data for tracking trends or identifying performance issues.