This document explains the purpose and logic behind each command used in
the Linux system monitoring script.
The script provides a quick overview of CPU, memory, disk, and running
processes to help with troubleshooting and performance checks.
This script is inspired by and aligned with the Server Stats project from roadmap.sh:
https://roadmap.sh/projects/server-stats
#!/bin/bash- Known as the shebang
- Tells Linux to execute the script using Bash
- Ensures consistent behavior across systems
cpu_idle=$(top -bn1 | grep "Cpu(s)" | awk '{print $8}')
cpu_usage=$(echo "100 - $cpu_idle" | bc)Command Purpose
top -bn1 Runs top in batch mode for 1 iteration
grep "Cpu(s)" Filters the CPU statistics line
awk '{print $8}' Extracts CPU idle percentage
bc Performs math calculation
CPU Usage = 100 − Idle %
free -m | awk 'NR==2{printf "Used: %dMB / Total: %dMB (%.2f%%)\n", $3, $2, $3*100/$2 }'Field Meaning
$3 Used memory
$2 Total memory
printf Formats clean readable output
Used: 2048MB / Total: 4096MB (50.00%)
df -h / | awk 'NR==2{printf "Used: %s / Total: %s (%s usage)\n", $3, $2, $5}'Field Meaning
$3 Used space
$2 Total space
$5 Percentage usage
Used: 15G / Total: 40G (38% usage)
ps -eo pid,ppid,cmd,%cpu --sort=-%cpu | head -n 6Option Purpose
ps -eo Lists all processes with custom format
--sort=-%cpu Sorts by highest CPU usage
head -n 6 Shows header + top 5 processes
Quickly identifies: - High CPU usage processes - Resource bottlenecks - Misbehaving services
- Linux (Ubuntu/Debian recommended)
- Works on most distributions
sudo apt update && sudo apt install bc -ysudo yum install bc -yMake script executable:
chmod +x monitor.shRun:
./monitor.shThis script provides:
- CPU usage
- Memory usage
- Disk usage
- Top resource-consuming processes
Useful for:
- Server health checks
- Troubleshooting
- Performance monitoring
- Cron automation
Author: frd amirul