How to Build a Simple Bash Script to Monitor CPU, Memory, and Disk Usage
This tutorial shows how to create a Bash script that continuously monitors a Linux server’s memory, disk, and CPU usage, explains the commands used, demonstrates assembling the data into variables, looping for a set period, logging results, and optionally applying a stress test to generate load.
1. Monitor Memory
free -m | awk 'NR==2{printf "%.2f%%\t\t", $3*100/$2 }'free -mdisplays used and free memory. Using awk we extract total and used values from the second line.
2. Monitor Disk
df -h | awk '$NF=="/"{printf "%s\t\t", $5}'df -hshows disk usage; the awk command selects the line for the root filesystem and prints the usage percentage.
3. Monitor CPU
top -bn1 | grep load | awk '{printf "%.2f%%\t\t
", $(NF-2)}'The top -bn1 command runs once in batch mode, grep load finds the load line, and awk extracts the load average as a CPU usage percentage.
These commands are stored in variables:
MEMORY=$(free -m | awk 'NR==2{printf "%.2f%%\t\t", $3*100/$2 }')
DISK=$(df -h | awk '$NF=="/"{printf "%s\t\t", $5}')
CPU=$(top -bn1 | grep load | awk '{printf "%.2f%%\t\t
", $(NF-2)}')A loop runs for a defined period (e.g., one hour) and prints the values every five seconds:
end=$((SECONDS+3600))
while [ $SECONDS -lt $end ]; do
echo "$MEMORY $DISK $CPU"
sleep 5
doneThe complete script prints a header and then the three columns:
#!/bin/bash
printf "Memory\t\tDisk\t\tCPU
"
end=$((SECONDS+3600))
while [ $SECONDS -lt $end ]; do
MEMORY=$(free -m | awk 'NR==2{printf "%.2f%%\t\t", $3*100/$2 }')
DISK=$(df -h | awk '$NF=="/"{printf "%s\t\t", $5}')
CPU=$(top -bn1 | grep load | awk '{printf "%.2f%%\t\t
", $(NF-2)}')
echo "$MEMORY $DISK $CPU"
sleep 5
doneRunning the script outputs lines such as "9.34% 7% 0.00%". The output can be redirected to a log file.
Stress Test
Install the stress tool (e.g., yum install stress) and run a load test, for example: stress -c 2 -i 1 -m 1 --vm-bytes 128M -t 3600s While the stress test runs, the monitoring script shows increased CPU and memory usage.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
