0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Monitor Server Health with CPU and Memory Usage

Use a Bash script with commands like top -bn1 for CPU, free -m for memory, and df -h for disk space, combined in a script to monitor server health.
📋

Examples

InputRun script on a server with 10% CPU, 2048MB free memory, 50% disk usage
OutputCPU Load: 10% Memory Usage: 1024MB used / 2048MB total Disk Usage: 50% used on /
InputRun script on a server with 85% CPU, 512MB free memory, 90% disk usage
OutputCPU Load: 85% Memory Usage: 3584MB used / 4096MB total Disk Usage: 90% used on /
InputRun script on a server with 0% CPU, 0MB free memory, 100% disk usage
OutputCPU Load: 0% Memory Usage: 8192MB used / 8192MB total Disk Usage: 100% used on /
🧠

How to Think About It

To monitor server health, gather key metrics like CPU load, memory usage, and disk space using simple system commands. Combine these commands in a script that runs them one after another and prints the results clearly for easy reading.
📐

Algorithm

1
Get current CPU load using a system command.
2
Get memory usage details using a system command.
3
Get disk usage information using a system command.
4
Format and print these values in a readable way.
💻

Code

bash
#!/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.

1

Get CPU load

Command output: 'Cpu(s): 15.3%us, ... idle 84.7%' → cpu_load=100 - 84.7 = 15.3%

2

Get memory usage

free -m output line: 'Mem: 4096 2048 2048 ...' → mem_used=2048, mem_total=4096

3

Get disk usage

df -h / output line: '/dev/sda1 100G 45G 55G 45% /' → disk_usage=45%

MetricValue
CPU Load15.3%
Memory Used2048 MB
Memory Total4096 MB
Disk Usage45%
💡

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

Using vmstat and awk
bash
#!/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 /"
vmstat gives a snapshot of CPU usage but requires waiting for 2 samples; slightly slower but more accurate.
Using sar command
bash
#!/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 /"
sar provides detailed system activity reports but may not be installed by default.

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.

ApproachTimeSpaceBest For
top commandO(1)O(1)Quick, default availability
vmstat commandO(1) but slowerO(1)More accurate CPU snapshot
sar commandO(1) but slowerO(1)Detailed system reports, requires install
💡
Run your monitoring script with cron to get regular server health updates automatically.
⚠️
Beginners often forget to use non-interactive options like -bn1 with top, causing the script to hang.