Build a System Resource Monitoring Script
This project builds sysmon.sh, a monitoring script for Linux servers. It measures CPU usage, memory, swap, load average and disk space, draws them as text meters, lists the busiest processes, and compares each value against a warning threshold. It works in three ways: as a one-shot report for a human, as a live dashboard that refreshes every few seconds, and as a CSV producer whose lines can be collected by cron into a history file. Its exit status tells a calling script or monitoring system whether any threshold was crossed.
Lesson 167 introduced the commands for checking CPU, memory and load. This project goes one level deeper: instead of parsing the human-oriented output of top or free, it reads the raw counters the kernel publishes in /proc, which is what those tools do internally. Along the way it deals with integer-only arithmetic, measuring rates, subshell pitfalls and terminal control.
What the Script Should Do
- Measure CPU usage (as a percentage over a short interval), memory in use, swap, the load average relative to the number of cores, and disk usage for one or more mount points.
- Compare CPU, memory and disk against thresholds (
-c,-m,-d, default 90%) and mark each valueOKorWARN. - Report for humans, with meters and readable units.
- Watch mode (
-w SECONDS) that redraws the report untilCtrl+C. - CSV output (
-o csv) for collecting a history. - Exit status 1 when any threshold is crossed, so
sysmon.sh || notify ...works.
Where the Numbers Come From
The /proc File System
/proc is not stored on disk. Every file in it is generated by the kernel at the moment it is read, so reading /proc/meminfo twice can give two different results. These files are plain text and are meant to be parsed. The script uses three of them, plus df, nproc and ps.
CPU Usage from /proc/stat
The first line of /proc/stat contains counters for all CPUs combined:
cpu 7062 0 4837 144593 60 0 79 247 0 0
Each number is the total time, since boot, that the CPUs spent in a certain state, measured in jiffies (usually hundredths of a second). The columns are:
| Column | Meaning |
|---|---|
| user | Running normal programs |
| nice | Running programs with lowered priority |
| system | Running kernel code |
| idle | Doing nothing |
| iowait | Idle while waiting for disk or network I/O |
| irq, softirq | Handling hardware and software interrupts |
| steal | Time a virtual machine wanted the CPU but the hypervisor gave it to someone else |
| guest, guest_nice | Running virtual machines (already included in user and nice) |
These counters only ever grow, so a single reading says nothing about current usage. CPU usage is a rate: read the counters twice, a known interval apart, and compare the differences:
usage = (busy₂ - busy₁) / (total₂ - total₁)
where total is the sum of the first eight columns and busy is total minus idle minus iowait. The guest columns are left out of the total because they are already counted in user and nice.
cpu_times() {
local label user nice system idle iowait irq softirq steal rest
read -r label user nice system idle iowait irq softirq steal rest < /proc/stat
local total=$(( user + nice + system + idle + iowait + irq + softirq + steal ))
echo "$(( total - idle - iowait )) $total"
}
read assigns the words of the first line to the variables in order; rest collects whatever is left (the guest columns), so the function keeps working if a future kernel adds columns. Redirecting a file into read reads only its first line, which is exactly the summary line.
The sample function calls cpu_times, sleeps one second, calls it again and computes the percentage. This one-second pause is why every report takes about a second to appear; top does the same thing between its refreshes.
Memory from /proc/meminfo
MemTotal: 8216124 kB
MemAvailable: 7661360 kB
SwapTotal: 0 kB
SwapFree: 0 kB
The important value is MemAvailable: the kernel's estimate of how much memory could be given to new programs without swapping. It is larger than MemFree, because Linux uses spare memory as a disk cache, and that cache is released when programs need the memory. A script that computed "used" as MemTotal - MemFree would report a healthy server as almost full. The script therefore uses MemTotal - MemAvailable as "used".
A small function reads one value without starting any external program:
meminfo() {
local key value unit
while read -r key value unit; do
[[ $key == "$1:" ]] && { echo "$value"; return; }
done < /proc/meminfo
echo 0
}
Load Average from /proc/loadavg
0.07 0.18 0.09 1/107 28000
The first three numbers are the average number of processes that were running or waiting to run (and on Linux, also those in uninterruptible disk wait) over the last 1, 5 and 15 minutes. A load of 2.0 means "two processes' worth of demand on average". Whether that is a lot depends on the number of CPU cores: 2.0 is full capacity on a 2-core machine but light on a 16-core server. The script therefore divides the 1-minute load by nproc and shows it as a percentage of capacity.
The load average is a moving average, so it lags behind reality. A CPU-heavy job that just started shows 100% CPU at once, while the 1-minute load needs about a minute to climb. The two numbers answer different questions: "how busy is the CPU right now" and "how much work has been queuing up recently".
Disk Usage from df
$ df -P -k / /dev/shm
Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/vda 264212084 12738056 31454780 29% /
tmpfs 8216124 0 8216124 0% /dev/shm
-P asks for the POSIX output format: exactly one line per file system, never wrapped, with fixed columns. Without it, a long device name can push the numbers onto a second line and break the parsing. -k makes the sizes 1-KiB blocks on every system. The script skips the header with tail -n +2, ignores pseudo file systems such as /proc whose capacity is -, and lists each mount point only once, because two paths on the same file system (/ and /tmp on many systems) produce identical lines.
Processes from ps
ps -eo pid=,comm=,pcpu=,pmem= --sort=-pcpu | head -n 5
-e selects every process, -o chooses the columns, and the = after each name suppresses the header. --sort=-pcpu sorts by CPU, highest first. One detail is worth knowing: ps computes %CPU as CPU time divided by the process's lifetime. A process that has been busy for one second after a week of idling still shows almost 0%. The report says so in its heading. For instantaneous per-process values, top -b -n 2 or pidstat measure over an interval, just like the script does for the whole system.
Design Decisions
Integer Arithmetic with One Decimal Place
Bash arithmetic has no fractions. The script keeps percentages in tenths: 734 means 73.4%. Calculations multiply by 1000 instead of 100, and add half the divisor before dividing to round correctly:
cpu=$(( ( (b2 - b1) * 1000 + (t2 - t1) / 2 ) / (t2 - t1) ))
Only when printing does fmt insert the decimal point:
fmt() { printf '%d.%d' $(( $1 / 10 )) $(( $1 % 10 )); }
The load average arrives as text with two decimals, like 0.09. Removing the dot (${load1/./}) turns it into hundredths (009). The 10# prefix forces base 10; without it, Bash would read 009 as an invalid octal number, because a leading zero means octal in arithmetic (lesson 49).
load_pct=$(( 10#${load1/./} * 10 / cores ))
Readable Sizes with numfmt
human() { numfmt --from-unit=1024 --to=iec-i --suffix=B --round=nearest --format='%.1f' "$1"; }
The sizes from /proc/meminfo and df -k are in KiB, so --from-unit=1024 scales them to bytes first. --to=iec-i chooses binary units with the Ki, Mi, Gi prefixes, and --round=nearest replaces numfmt's default of rounding away from zero, which would show 7.83 GiB as 7.9.
A Subshell Pitfall: Counting Warnings
The first version of the threshold check printed OK or WARN and was used like this:
printf '... %s\n' "$(check "$cpu" "$cpu_limit")" # the warning count is lost
It printed the right word, but the script never exited with status 1. The reason is that $( ) runs the function in a subshell, a copy of the shell process. The function incremented warnings in that copy, and the copy disappeared when the substitution ended. The fix is to call the function directly and have it set a variable instead of printing:
check() {
if (( $1 >= $2 * 10 )); then
warnings=$((warnings + 1))
state=WARN
else
state=OK
fi
}
check "$cpu" "$cpu_limit"
printf '%-8s %s %6s%% %s\n' CPU "$(bar "$cpu")" "$(fmt "$cpu")" "$state"
Any function that must change the caller's variables must run in the current shell. Lessons 93 and 192 showed the same effect from other angles.
Text Meters
bar() {
local filled=$(( ($1 * 30 + 500) / 1000 )) full empty
printf -v full '%*s' "$filled" ''
printf -v empty '%*s' $(( 30 - filled )) ''
printf '[%s%s]' "${full// /#}" "${empty// /.}"
}
The meter is 30 characters wide. For a percentage in tenths, the number of filled characters is tenths * 30 / 1000, rounded. printf -v builds strings of spaces of the right lengths, and pattern substitution turns them into # and . characters.
Watch Mode Without Flicker
A dashboard that clears the screen and then spends a second measuring would show an empty screen for that second. The watch loop instead builds the complete report first, and only then clears and prints it in one go:
screen=$(report) # build first, then draw at once
[[ -t 1 ]] && tput clear
printf '%s\n\n(refreshing every %ss, Ctrl+C to stop)\n' "$screen" "$interval"
tput clearlooks up the correct escape sequence for the current terminal in the terminfo database, instead of hard-coding one.tput civishides the cursor while the dashboard runs, andtput cnormrestores it. TheINTtrap restores the cursor when the user pressesCtrl+C; without it, the terminal would be left without a visible cursor.[[ -t 1 ]]tests whether standard output is a terminal. When the output is redirected to a file, the script skips the terminal control sequences, which would otherwise end up as garbage in the file.- The sampling already takes one second, so the loop sleeps for
interval - 1seconds to keep the refresh interval accurate.
CSV for History
A single report shows the present. A file with one line per measurement, collected over days, shows trends: memory that grows every day, or a disk that will be full in three weeks. CSV mode prints one line per mount point, so each line is self-contained and easy to filter or import into a spreadsheet:
time,host,cpu_pct,mem_pct,load1,cores,disk_mount,disk_pct
2026-12-02T17:17:03,vm,1.0,6.7,0.09,2,/,29
The time stamp uses the ISO 8601 format (2026-12-02T17:17:03), which sorts correctly as text and is understood by spreadsheet programs and databases.
The Complete Script
#!/usr/bin/env bash
#
# sysmon.sh - report CPU, memory, load and disk usage, with warning thresholds
#
# Usage: sysmon.sh [-w SECONDS] [-o csv] [-c PCT] [-m PCT] [-d PCT] [MOUNT...]
#
# Options:
# -w SECONDS watch mode: refresh every SECONDS until Ctrl+C
# -o csv print one CSV line per sample instead of the report
# -c PCT CPU warning threshold in percent (default: 90)
# -m PCT memory warning threshold in percent (default: 90)
# -d PCT disk warning threshold in percent (default: 90)
# -h show this help
#
# MOUNTs are the file systems to check (default: /). Linux only: reads /proc.
#
# Exit status (single sample): 0 all values below the thresholds,
# 1 at least one warning, 2 usage error.
set -euo pipefail
readonly PROG=${0##*/}
usage() { sed -n '3,19s/^# \{0,1\}//p' "$0"; }
die() {
printf '%s: %s\n' "$PROG" "$1" >&2
exit "${2:-2}"
}
interval=0 format=report
cpu_limit=90 mem_limit=90 disk_limit=90
while getopts ':w:o:c:m:d:h' opt; do
case $opt in
w) interval=$OPTARG ;;
o) format=$OPTARG ;;
c) cpu_limit=$OPTARG ;;
m) mem_limit=$OPTARG ;;
d) disk_limit=$OPTARG ;;
h) usage; exit 0 ;;
:) die "option -$OPTARG needs a value" ;;
*) die "unknown option -$OPTARG (try -h)" ;;
esac
done
shift $((OPTIND - 1))
[[ $interval =~ ^[0-9]+$ ]] || die "-w needs a whole number of seconds"
[[ $format == report || $format == csv ]] || die "-o must be 'csv'"
for limit in "$cpu_limit" "$mem_limit" "$disk_limit"; do
[[ $limit =~ ^[0-9]+$ ]] && (( limit <= 100 )) || die "thresholds must be whole numbers from 0 to 100"
done
[[ -r /proc/stat && -r /proc/meminfo ]] || die "this script needs Linux /proc" 1
mounts=("$@")
(( ${#mounts[@]} > 0 )) || mounts=(/)
for m in "${mounts[@]}"; do
[[ -d $m ]] || die "not a directory: $m"
done
# --- measurements ---------------------------------------------------------------
# Percentages are kept in tenths (734 means 73.4%) so that Bash's integer
# arithmetic can work with one decimal place.
# cpu_times - print "busy total" jiffies from the first line of /proc/stat
cpu_times() {
local label user nice system idle iowait irq softirq steal rest
read -r label user nice system idle iowait irq softirq steal rest < /proc/stat
local total=$(( user + nice + system + idle + iowait + irq + softirq + steal ))
echo "$(( total - idle - iowait )) $total"
}
# meminfo KEY - print a value in kB from /proc/meminfo
meminfo() {
local key value unit
while read -r key value unit; do
[[ $key == "$1:" ]] && { echo "$value"; return; }
done < /proc/meminfo
echo 0
}
# fmt TENTHS - print 734 as 73.4
fmt() { printf '%d.%d' $(( $1 / 10 )) $(( $1 % 10 )); }
# human KB - print a size in kB in readable units
human() { numfmt --from-unit=1024 --to=iec-i --suffix=B --round=nearest --format='%.1f' "$1"; }
# bar TENTHS - print a 30-character meter for a percentage
bar() {
local filled=$(( ($1 * 30 + 500) / 1000 )) full empty
printf -v full '%*s' "$filled" ''
printf -v empty '%*s' $(( 30 - filled )) ''
printf '[%s%s]' "${full// /#}" "${empty// /.}"
}
# sample - take one set of measurements into global variables
sample() {
local b1 t1 b2 t2
read -r b1 t1 < <(cpu_times)
sleep 1 # CPU usage is a rate: measure over 1 s
read -r b2 t2 < <(cpu_times)
cpu=0
(( t2 > t1 )) && cpu=$(( ( (b2 - b1) * 1000 + (t2 - t1) / 2 ) / (t2 - t1) ))
mem_total=$(meminfo MemTotal)
mem_avail=$(meminfo MemAvailable)
mem_used=$(( mem_total - mem_avail ))
mem=$(( (mem_used * 1000 + mem_total / 2) / mem_total ))
swap_total=$(meminfo SwapTotal)
swap_used=$(( swap_total - $(meminfo SwapFree) ))
read -r load1 load5 load15 _ < /proc/loadavg
cores=$(nproc)
disks=()
local fs blocks used avail capacity mount
local -A seen=()
while read -r fs blocks used avail capacity mount; do
[[ $capacity =~ ^[0-9]+%$ ]] || continue # pseudo file systems like /proc
[[ -n ${seen[$mount]:-} ]] && continue # two paths on one file system
seen[$mount]=1
disks+=("$mount|${capacity%\%}|$used|$blocks")
done < <(df -P -k -- "${mounts[@]}" | tail -n +2)
}
# check TENTHS LIMIT - set state to OK or WARN and count warnings.
# It sets a variable instead of printing, because a function called inside
# $( ) runs in a subshell and could not update the warnings counter.
check() {
if (( $1 >= $2 * 10 )); then
warnings=$((warnings + 1))
state=WARN
else
state=OK
fi
}
# --- output ---------------------------------------------------------------------
report() {
local d mount pct used blocks load_pct state
warnings=0
printf 'System report for %s at %s\n\n' "$(hostname)" "$(date '+%Y-%m-%d %H:%M:%S')"
check "$cpu" "$cpu_limit"
printf '%-8s %s %6s%% %s\n' CPU "$(bar "$cpu")" "$(fmt "$cpu")" "$state"
check "$mem" "$mem_limit"
printf '%-8s %s %6s%% %-4s %s of %s used\n' Memory "$(bar "$mem")" "$(fmt "$mem")" \
"$state" "$(human "$mem_used")" "$(human "$mem_total")"
if (( swap_total > 0 )); then
printf '%-8s %s of %s used\n' Swap "$(human "$swap_used")" "$(human "$swap_total")"
else
printf '%-8s none configured\n' Swap
fi
# load per core in tenths of a percent: 0.50 on 2 cores = 25.0%
load_pct=$(( 10#${load1/./} * 10 / cores ))
printf '%-8s %s %s %s (%d cores, %s%% of capacity)\n' Load "$load1" "$load5" "$load15" \
"$cores" "$(fmt "$load_pct")"
printf '\nDisks\n'
for d in "${disks[@]}"; do
IFS='|' read -r mount pct used blocks <<< "$d"
check $(( pct * 10 )) "$disk_limit"
printf ' %-12s %s %5s%% %-4s %s of %s used\n' "$mount" "$(bar $(( pct * 10 )))" "$pct" \
"$state" "$(human "$used")" "$(human "$blocks")"
done
printf '\nTop processes by CPU (average over each process lifetime)\n'
printf ' %7s %-16s %5s %5s\n' PID COMMAND %CPU %MEM
ps -eo pid=,comm=,pcpu=,pmem= --sort=-pcpu | head -n 5 |
while read -r pid comm pcpu pmem; do
printf ' %7s %-16s %5s %5s\n' "$pid" "$comm" "$pcpu" "$pmem"
done
}
csv_header() { echo "time,host,cpu_pct,mem_pct,load1,cores,disk_mount,disk_pct"; }
csv_line() {
local d mount pct _ state
warnings=0
check "$cpu" "$cpu_limit"
check "$mem" "$mem_limit"
for d in "${disks[@]}"; do
IFS='|' read -r mount pct _ <<< "$d"
check $(( pct * 10 )) "$disk_limit"
printf '%s,%s,%s,%s,%s,%s,%s,%s\n' "$(date '+%Y-%m-%dT%H:%M:%S')" "$(hostname)" \
"$(fmt "$cpu")" "$(fmt "$mem")" "$load1" "$cores" "$mount" "$pct"
done
}
# --- main ----------------------------------------------------------------------
if (( interval == 0 )); then
sample
if [[ $format == csv ]]; then
csv_header
csv_line
else
report
fi
(( warnings == 0 )) || exit 1
exit 0
fi
# watch mode: repeat until interrupted
trap '[[ $format == report && -t 1 ]] && tput cnorm; echo; exit 0' INT TERM
[[ $format == csv ]] && csv_header
[[ $format == report && -t 1 ]] && tput civis # hide the cursor while redrawing
while true; do
sample
if [[ $format == csv ]]; then
csv_line
else
screen=$(report) # build first, then draw at once
[[ -t 1 ]] && tput clear
printf '%s\n\n(refreshing every %ss, Ctrl+C to stop)\n' "$screen" "$interval"
fi
(( interval > 1 )) && sleep $(( interval - 1 )) # sample already took 1 s
done
Running the Monitor
A One-Shot Report
$ ./sysmon.sh; echo "status $?"
System report for vm at 2026-12-02 17:17:09
CPU [#.............................] 4.0% OK
Memory [##............................] 6.8% OK 548.8MiB of 7.8GiB used
Swap none configured
Load 0.09 0.16 0.09 (2 cores, 4.5% of capacity)
Disks
/ [#########.....................] 29% OK 12.1GiB of 252.0GiB used
Top processes by CPU (average over each process lifetime)
PID COMMAND %CPU %MEM
85 claude 2.2 4.6
1 process_api 0.0 0.0
22 ksoftirqd/1 0.0 0.0
14 ksoftirqd/0 0.0 0.0
210 environment-man 0.0 0.4
status 0
This is a quiet two-core virtual machine with no swap configured. Memory usage is low, and the disk is 29% full.
Under Load
To see the thresholds at work, start two CPU-bound processes, one per core. yes prints y endlessly, and sending its output to /dev/null makes it a pure CPU consumer:
$ yes > /dev/null & yes > /dev/null &
$ ./sysmon.sh -c 80; echo "status $?"
System report for vm at 2026-12-02 17:17:12
CPU [##############################] 100.0% WARN
Memory [##............................] 6.8% OK 546.8MiB of 7.8GiB used
Swap none configured
Load 0.09 0.16 0.09 (2 cores, 4.5% of capacity)
Disks
/ [#########.....................] 29% OK 12.1GiB of 252.0GiB used
Top processes by CPU (average over each process lifetime)
PID COMMAND %CPU %MEM
28407 yes 99.0 0.0
28406 yes 97.7 0.0
85 claude 2.2 4.6
28409 bash 0.9 0.0
1 process_api 0.0 0.0
status 1
$ kill %1 %2
- CPU is at 100% and above the threshold of 80%, so it is marked
WARNand the exit status is 1. - Load is still 0.09: the processes had been running for only two seconds, and the 1-minute average needs time to rise.
- The process list shows the two
yesprocesses at the top. They are new, so their lifetime average is close to their current usage.
Checking Several File Systems
$ ./sysmon.sh -o csv / /tmp /proc /dev/shm
time,host,cpu_pct,mem_pct,load1,cores,disk_mount,disk_pct
2026-12-02T17:17:03,vm,1.0,6.7,0.09,2,/,29
2026-12-02T17:17:03,vm,1.0,6.7,0.09,2,/dev/shm,0
/tmp is part of the root file system on this machine, so it is not listed twice, and /proc is skipped because it has no capacity.
Watching Live
$ ./sysmon.sh -w 5
The screen is redrawn every five seconds until Ctrl+C. Combined with CSV output, watch mode becomes a simple recorder; timeout ends it after a fixed time:
$ timeout -s INT 7 ./sysmon.sh -w 2 -o csv
time,host,cpu_pct,mem_pct,load1,cores,disk_mount,disk_pct
2026-12-02T17:16:28,vm,0.0,6.8,0.18,2,/,29
2026-12-02T17:16:30,vm,1.0,6.7,0.17,2,/,29
2026-12-02T17:16:32,vm,1.5,6.7,0.17,2,/,29
Input Errors
$ ./sysmon.sh -w x
sysmon.sh: -w needs a whole number of seconds
$ ./sysmon.sh -o json
sysmon.sh: -o must be 'csv'
$ ./sysmon.sh -c 150
sysmon.sh: thresholds must be whole numbers from 0 to 100
$ ./sysmon.sh /nope
sysmon.sh: not a directory: /nope
All of these exit with status 2.
Scheduling and Alerting
Two crontab entries (lesson 170) turn the script into a small monitoring system. The first records a CSV line every five minutes; tail -n +2 drops the header so it appears only once in the history file. The second checks thresholds every ten minutes and sends a notification when one is crossed:
*/5 * * * * /usr/local/bin/sysmon.sh -o csv / /home | tail -n +2 >> /var/log/sysmon.csv
*/10 * * * * /usr/local/bin/sysmon.sh -c 95 -m 90 -d 85 > /tmp/sysmon.txt || /usr/local/bin/notify.sh "Resource warning on $(hostname)" < /tmp/sysmon.txt
notify.sh stands for any notification script, such as the one built in lesson 173. Because the report is captured in a file first, the notification contains the full report, including the process list that often explains the problem.
With a few weeks of CSV data, standard tools answer trend questions. For example, the highest memory usage recorded per day:
awk -F, '{ day = substr($1, 1, 10); if ($4 > max[day]) max[day] = $4 }
END { for (d in max) print d, max[d] }' /var/log/sysmon.csv | sort
Ideas for Extending the Project
- Per-core CPU.
/proc/statalso has linescpu0,cpu1and so on. Showing each core reveals single-threaded programs that keep one core at 100% while the average looks moderate. - Disk and network throughput.
/proc/diskstatsand/proc/net/devcontain growing byte counters, just like/proc/stat. Applying the same two-sample technique gives read/write and receive/transmit rates. - Pressure stall information. On modern kernels,
/proc/pressure/cpu,memoryandioreport how much time tasks spent waiting for each resource, often a better warning signal than raw usage. - Hysteresis for alerts. To avoid a notification storm when a value hovers around the threshold, alert only after several consecutive warnings, keeping the count in a small state file.
- JSON output. An
-o jsonmode would let the script feed tools likejqor a web dashboard.