Bash Script to Monitor Server Health with CPU and Memory Usage
top -bn1 for CPU, free -m for memory, and df -h for disk space, combined in a script to monitor server health.Examples
How to Think About It
Algorithm
Code
#!/bin/bash cpu_load=$(top -bn1 | grep 'Cpu(s)' | awk '{print 100 - $8"%"}') mem_used=$(free -m | awk '/Mem:/ {print $3}') mem_total=$(free -m | awk '/Mem:/ {print $2}') disk_usage=$(df -h / | awk 'NR==2 {print $5}') echo "CPU Load: $cpu_load" echo "Memory Usage: $mem_used MB used / $mem_total MB total" echo "Disk Usage: $disk_usage used on /"
Dry Run
Let's trace the script running on a server with 15.3% CPU load, 2048MB used memory out of 4096MB, and 45% disk usage.
Get CPU load
Command output: 'Cpu(s): 15.3%us, ... idle 84.7%' → cpu_load=100 - 84.7 = 15.3%
Get memory usage
free -m output line: 'Mem: 4096 2048 2048 ...' → mem_used=2048, mem_total=4096
Get disk usage
df -h / output line: '/dev/sda1 100G 45G 55G 45% /' → disk_usage=45%
| Metric | Value |
|---|---|
| CPU Load | 15.3% |
| Memory Used | 2048 MB |
| Memory Total | 4096 MB |
| Disk Usage | 45% |
Why This Works
Step 1: CPU Load Calculation
The script uses top -bn1 to get CPU stats and calculates CPU usage by subtracting idle percentage from 100.
Step 2: Memory Usage Extraction
It uses free -m to get memory in megabytes and extracts used and total memory values.
Step 3: Disk Usage Check
It runs df -h / to get disk usage of the root partition and extracts the used percentage.
Alternative Approaches
#!/bin/bash cpu_load=$(vmstat 1 2 | tail -1 | awk '{print 100 - $15"%"}') mem_used=$(free -m | awk '/Mem:/ {print $3}') mem_total=$(free -m | awk '/Mem:/ {print $2}') disk_usage=$(df -h / | awk 'NR==2 {print $5}') echo "CPU Load: $cpu_load" echo "Memory Usage: $mem_used MB used / $mem_total MB total" echo "Disk Usage: $disk_usage used on /"
#!/bin/bash cpu_load=$(sar 1 1 | grep Average | awk '{print 100 - $8"%"}') mem_used=$(free -m | awk '/Mem:/ {print $3}') mem_total=$(free -m | awk '/Mem:/ {print $2}') disk_usage=$(df -h / | awk 'NR==2 {print $5}') echo "CPU Load: $cpu_load" echo "Memory Usage: $mem_used MB used / $mem_total MB total" echo "Disk Usage: $disk_usage used on /"
Complexity: O(1) time, O(1) space
Time Complexity
The script runs a fixed number of system commands once, so time complexity is constant O(1).
Space Complexity
It uses a few variables to store command outputs, so space complexity is constant O(1).
Which Approach is Fastest?
Using top -bn1 is fast and available by default; vmstat and sar may be slower or require installation.
| Approach | Time | Space | Best For |
|---|---|---|---|
| top command | O(1) | O(1) | Quick, default availability |
| vmstat command | O(1) but slower | O(1) | More accurate CPU snapshot |
| sar command | O(1) but slower | O(1) | Detailed system reports, requires install |
-bn1 with top, causing the script to hang.