Build a Server Health-Check and Alert Script
This project builds healthcheck.sh, a script that reads a list of checks from a file, runs them, and sends an alert when something is really wrong. The checks cover the things that usually break a server: a file system that is nearly full, memory or CPU load that is too high, a program that has stopped, a network port that does not answer, and a web address that returns an error. What makes it a monitoring tool and not just a list of commands is the alert logic: it alerts once when a problem is confirmed, it stays silent while the problem continues, and it sends one more message when the problem is over.
Earlier lessons built the individual parts. Lesson 166 measured disk space, lesson 167 CPU and memory, lesson 168 websites with curl, lesson 172 a simple health-check script, and lesson 173 notifications. This project combines them and adds what makes alerts bearable for the people who receive them: a confirmation period and a memory of the previous results.
What the Script Should Do
- Read the checks from a file, one per line, with comments allowed.
- Run six kinds of checks:
disk,mem,load,process,portandurl. - Remember the result of each check between runs, in a state directory.
- Confirm a problem before reporting it: a check must fail several runs in a row (
-n, default 2) so that a short hiccup does not wake anybody up. - Alert once per problem and once more when it recovers, through any program given with
-a. - Exit with status 1 while any check is failing, so other tools can use the result.
The Check File
A check file is plain text. Everything after # is a comment, and blank lines are ignored:
# what must be true on this server
disk / 90
mem 90
load 150
process sleep
port 127.0.0.1 8097
url http://127.0.0.1:8097/
| Line | The check fails when |
|---|---|
disk / 90 | The file system mounted at / is more than 90% full |
mem 90 | More than 90% of the memory is in use (without the cache that the system can release) |
load 150 | The 1-minute load average is above 150% of the number of CPU cores |
process sleep | No process has exactly the name sleep |
port 127.0.0.1 8097 | A TCP connection to that address and port is refused or times out |
url http://... | The HTTP request fails or returns a status other than 2xx or 3xx |
A load of 100% means that, on average, every core always has one process to run. Values above 100% mean that processes have to wait. A limit of 150% is a reasonable warning level for many servers, but the right value depends on the work the server does.
Design Decisions
One Function per Check
Every check is a small function that does two things: it sets the variable msg to a short description of the result, and it returns status 0 when the check passed and 1 when it failed. This is the pattern used for conditions in lesson 90:
check_disk() {
local mount=$1 limit=$2 cap
[[ -d $mount ]] || { msg="$mount does not exist"; return 1; }
read -r _ _ _ _ cap _ < <(df -P -k -- "$mount" | tail -n +2)
cap=${cap%\%}
msg="$mount is ${cap}% full (limit ${limit}%)"
(( cap <= limit ))
}
The last line is an arithmetic test, and its result becomes the return value of the function. The functions are always called directly and never inside $( ), because a command substitution runs in a subshell and the value of msg would be lost (the rule from lessons 93 and 197). The message is built in all cases, also when the check passes, so the report always shows the current value.
df -P prints the POSIX format with one line per file system, and read splits it into fields. The fifth field is the capacity, for example 29%, and the line cap=${cap%\%} removes the percent sign so that it can be used in arithmetic.
Checking a Port Without Extra Tools
Bash can open a network connection by itself. A redirection to the special path /dev/tcp/HOST/PORT creates a TCP connection:
timeout 3 bash -c 'exec 3<>"/dev/tcp/$0/$1"' 127.0.0.1 8097
echo $?
Expected output while a server listens on port 8097:
0
and 1 (connection refused) when nothing listens. The special file does not exist on the disk; Bash itself handles it. The details:
exec 3<>fileopens the connection on file descriptor 3, for reading and writing. It succeeds only if the connection could be made.- The code runs in a small
bash -ccommand so that a failing connection never ends the main script, and so thattimeout 3can stop it after three seconds if the destination does not answer at all (for example when a firewall silently drops the packets). - The host and port are given as the arguments
$0and$1of the little script and are not pasted into the text of the command. If the check file ever contained something unusual, it could not be run as a command.
This is the check to use for services that do not speak HTTP, such as databases, mail servers and SSH.
Memory and Load Without Parsing Tool Output
The memory check reads /proc/meminfo and uses MemAvailable, the kernel's own estimate of memory that can be given to programs without swapping. Using MemFree instead would report a healthy server as full, because Linux fills spare memory with the file cache (lesson 197 explains this in detail).
The load check reads /proc/loadavg, removes the dot from the first value (0.09 becomes 009), and divides by the number of cores. The value 009 means nine hundredths of a load, which is also 9 percent of one core, so dividing by the core count gives a percentage without any decimal arithmetic. The prefix 10# forces base 10, so that 009 is not read as an invalid octal number:
pct=$(( 10#${load1/./} / cores ))
Remembering Results Between Runs
A health check runs again and again, typically from cron every minute or every five minutes. To know whether a failure is new or old, each check has a small state file in the state directory. It holds two numbers: how many runs in a row the check has failed, and whether an alert has already been sent for this problem.
key=${kind}_${arg1:-}_${arg2:-}
statefile=$statedir/${key//[^A-Za-z0-9._-]/_}
fails=0 alerted=0
[[ -r $statefile ]] && read -r fails alerted < "$statefile"
The check disk / 90 becomes the key disk_/_90. Characters that are unsafe in file names, such as / and :, are replaced by an underscore with a pattern substitution (${key//[^A-Za-z0-9._-]/_}). On the first run no state file exists, so the defaults of 0 and 0 apply.
The Alert Rules
The rules fit into a few lines, and they are the heart of the script:
if (( ok == 0 )); then
if (( alerted )); then
events+=("RECOVERED $msg")
fi
fails=0 alerted=0
else
fails=$((fails + 1))
if (( fails >= runs && ! alerted )); then
events+=("PROBLEM $msg (failed $fails run(s) in a row)")
alerted=1
fi
fi
- A passing check resets the counter. If an alert had been sent earlier, a
RECOVEREDevent is added, and the person who received the problem report learns that it is over. - A failing check increases the counter. Only when the counter reaches the configured number and no alert has been sent yet does a
PROBLEMevent appear. After that,alertedstays 1, so the script is silent during the rest of the outage.
The result is exactly one message when a problem starts and one when it ends, no matter how long it lasts. Without this memory, a check every minute would send 60 mails an hour about the same full disk.
Reading the Check File on Its Own Descriptor
The main loop reads the check file line by line. Some of the commands inside the loop talk to the network or start other programs, and a program that reads standard input would take lines from the check file and make the loop end early, with no error message. The script therefore opens the file on its own file descriptor 8 and reads from there:
while read -r -u 8 kind arg1 arg2 _ || [[ -n ${kind:-} ]]; do
...
done 8< "$checkfile"
read -u 8 reads from descriptor 8, and done 8< file opens it for the loop. Standard input stays untouched. The condition || [[ -n ${kind:-} ]] makes sure that a last line without a newline at the end is still processed (lesson 114).
Delivering the Alert
The script does not know how to send mail, SMS or chat messages. It calls a program given with -a, passes the subject as the first argument and the message on standard input. Any program that follows this rule works, for example a small wrapper around mail, curl to a chat webhook (lesson 173), or just a script that appends to a file, as in the tests below. Without -a, the alert is printed, which is useful for tests and for cron (which mails any output to the owner of the job).
The Complete Script
#!/usr/bin/env bash
#
# healthcheck.sh - run the checks listed in a file and alert on confirmed problems
#
# Usage: healthcheck.sh [-s DIR] [-n RUNS] [-a COMMAND] [-q] CHECKFILE
#
# Options:
# -s DIR directory that remembers the result of earlier runs
# (default: /var/tmp/healthcheck)
# -n RUNS a check must fail RUNS runs in a row before an alert is sent
# (default: 2)
# -a COMMAND program that delivers an alert: it gets the subject as its first
# argument and the message on standard input (default: print it)
# -q print nothing when everything is fine
# -h show this help
#
# CHECKFILE has one check per line ("#" starts a comment). A check fails when:
# disk MOUNT PERCENT file system fuller than PERCENT
# mem PERCENT memory in use above PERCENT
# load PERCENT 1-minute load above PERCENT of the CPU cores
# process NAME no process with exactly this name
# port HOST PORT TCP connection refused or timed out
# url URL HTTP request fails or returns an error status
#
# Exit status: 0 every check passed, 1 at least one check failed, 2 usage error.
set -euo pipefail
export LC_ALL=C
readonly PROG=${0##*/}
usage() { sed -n '3,29s/^# \{0,1\}//p' "$0"; }
die() {
printf '%s: %s\n' "$PROG" "$1" >&2
exit 2
}
statedir=/var/tmp/healthcheck runs=2 alert_cmd= quiet=0
while getopts ':s:n:a:qh' opt; do
case $opt in
s) statedir=$OPTARG ;;
n) runs=$OPTARG ;;
a) alert_cmd=$OPTARG ;;
q) quiet=1 ;;
h) usage; exit 0 ;;
:) die "option -$OPTARG needs a value" ;;
*) die "unknown option -$OPTARG (try -h)" ;;
esac
done
shift $((OPTIND - 1))
[[ $runs =~ ^[1-9][0-9]*$ ]] || die "-n needs a whole number of at least 1"
(( $# == 1 )) || die "give exactly one check file (try -h)"
checkfile=$1
[[ -r $checkfile ]] || die "cannot read $checkfile"
[[ -z $alert_cmd ]] || command -v "${alert_cmd%% *}" >/dev/null || die "alert command not found: $alert_cmd"
mkdir -p "$statedir"
# --- the checks -----------------------------------------------------------------
# Each check sets $msg (a short explanation) and returns 0 when the check passed.
# They are called directly, never inside $( ), so that they can set variables.
check_disk() {
local mount=$1 limit=$2 cap
[[ -d $mount ]] || { msg="$mount does not exist"; return 1; }
read -r _ _ _ _ cap _ < <(df -P -k -- "$mount" | tail -n +2)
cap=${cap%\%}
msg="$mount is ${cap}% full (limit ${limit}%)"
(( cap <= limit ))
}
check_mem() {
local limit=$1 key value unit total=0 avail=0 pct
while read -r key value unit; do
case $key in
MemTotal:) total=$value ;;
MemAvailable:) avail=$value ;;
esac
done < /proc/meminfo
(( total > 0 )) || { msg="cannot read /proc/meminfo"; return 1; }
pct=$(( (total - avail) * 100 / total ))
msg="memory in use is ${pct}% (limit ${limit}%)"
(( pct <= limit ))
}
check_load() {
local limit=$1 load1 cores pct
read -r load1 _ < /proc/loadavg
cores=$(nproc)
pct=$(( 10#${load1/./} / cores )) # hundredths of a load per core = percent
msg="load is ${pct}% of $cores core(s) (limit ${limit}%)"
(( pct <= limit ))
}
check_process() {
if pgrep -x -- "$1" > /dev/null; then
msg="process $1 is running"
else
msg="process $1 is NOT running"
return 1
fi
}
check_port() {
if timeout 3 bash -c 'exec 3<>"/dev/tcp/$0/$1"' "$1" "$2" 2>/dev/null; then
msg="$1:$2 accepts connections"
else
msg="$1:$2 does NOT accept connections"
return 1
fi
}
check_url() {
local code
code=$(curl -s -o /dev/null --max-time 5 -w '%{http_code}' -- "$1" || true)
msg="$1 answered HTTP $code"
[[ $code =~ ^[23] ]]
}
# --- run every check, remember the result, collect events ----------------------
events=() # lines for the alert message
failing=0 total=0
while read -r -u 8 kind arg1 arg2 _ || [[ -n ${kind:-} ]]; do
[[ -z ${kind:-} || $kind == \#* ]] && { kind=; continue; }
total=$((total + 1))
case $kind in
disk) [[ -n ${arg2:-} ]] || die "disk needs MOUNT and PERCENT"; ok=0; check_disk "$arg1" "$arg2" || ok=1 ;;
mem) [[ -n ${arg1:-} ]] || die "mem needs PERCENT"; ok=0; check_mem "$arg1" || ok=1 ;;
load) [[ -n ${arg1:-} ]] || die "load needs PERCENT"; ok=0; check_load "$arg1" || ok=1 ;;
process) [[ -n ${arg1:-} ]] || die "process needs NAME"; ok=0; check_process "$arg1" || ok=1 ;;
port) [[ -n ${arg2:-} ]] || die "port needs HOST and PORT"; ok=0; check_port "$arg1" "$arg2" || ok=1 ;;
url) [[ -n ${arg1:-} ]] || die "url needs a URL"; ok=0; check_url "$arg1" || ok=1 ;;
*) die "unknown check '$kind' in $checkfile" ;;
esac
# one state file per check: "FAILS_IN_A_ROW ALERT_SENT"
key=${kind}_${arg1:-}_${arg2:-}
statefile=$statedir/${key//[^A-Za-z0-9._-]/_}
fails=0 alerted=0
[[ -r $statefile ]] && read -r fails alerted < "$statefile"
if (( ok == 0 )); then
status=" ok "
if (( alerted )); then
events+=("RECOVERED $msg")
fi
fails=0 alerted=0
else
failing=$((failing + 1))
fails=$((fails + 1))
status="FAIL"
if (( fails >= runs && ! alerted )); then
events+=("PROBLEM $msg (failed $fails run(s) in a row)")
alerted=1
fi
fi
echo "$fails $alerted" > "$statefile"
(( quiet && ok == 0 )) || printf '[%s] %-10s %s\n' "$status" "$kind" "$msg"
kind=
done 8< "$checkfile" # a separate file descriptor: commands in the loop cannot steal these lines
(( total > 0 )) || die "$checkfile contains no checks"
# --- deliver the alert -----------------------------------------------------------
if (( ${#events[@]} > 0 )); then
subject="Health check on $(hostname): ${#events[@]} change(s)"
body=$(printf 'Host: %s\nTime: %s\n\n' "$(hostname)" "$(date '+%Y-%m-%d %H:%M:%S')"
printf '%s\n' "${events[@]}")
if [[ -n $alert_cmd ]]; then
# shellcheck disable=SC2086 # the command may contain its own arguments
printf '%s\n' "$body" | $alert_cmd "$subject"
else
printf '\n%s\n%s\n' "$subject" "$body"
fi
fi
(( failing == 0 ))
Running the Health Check
The tests use a small web server on port 8097 (python3 -m http.server 8097 --bind 127.0.0.1) and a sleep process as the monitored program. The alert program notify.sh appends everything it receives to alerts.log:
#!/usr/bin/env bash
# test alert program: append the subject and the message to alerts.log
{ echo "=== ALERT: $1"; cat; echo; } >> "$(dirname "$0")/alerts.log"
Run 1: Everything Is Fine
$ ./healthcheck.sh -s st checks.conf; echo "status $?"
[ ok ] disk / is 29% full (limit 90%)
[ ok ] mem memory in use is 6% (limit 90%)
[ ok ] load load is 0% of 2 core(s) (limit 150%)
[ ok ] process process sleep is running
[ ok ] port 127.0.0.1:8097 accepts connections
[ ok ] url http://127.0.0.1:8097/ answered HTTP 200
status 0
The option -s st puts the state files in the directory st. Every check shows the current value, not only the word "ok", so the log of a successful run is also useful.
Run 2: The Web Server Stops (First Failure)
$ ./healthcheck.sh -s st -a ./notify.sh checks.conf; echo "status $?"
[ ok ] disk / is 29% full (limit 90%)
[ ok ] mem memory in use is 6% (limit 90%)
[ ok ] load load is 0% of 2 core(s) (limit 150%)
[ ok ] process process sleep is running
[FAIL] port 127.0.0.1:8097 does NOT accept connections
[FAIL] url http://127.0.0.1:8097/ answered HTTP 000
status 1
Two checks fail and the exit status is 1, but no alert is sent yet: alerts.log does not exist. The default confirmation period is two runs, and this is the first failure. A restart that takes a few seconds, or one lost packet, would never be reported.
Run 3: The Problem Is Confirmed
$ ./healthcheck.sh -s st -a ./notify.sh checks.conf; echo "status $?"
[ ok ] disk / is 29% full (limit 90%)
...
[FAIL] port 127.0.0.1:8097 does NOT accept connections
[FAIL] url http://127.0.0.1:8097/ answered HTTP 000
status 1
$ cat alerts.log
=== ALERT: Health check on vm: 2 change(s)
Host: vm
Time: 2026-12-02 17:44:44
PROBLEM 127.0.0.1:8097 does NOT accept connections (failed 2 run(s) in a row)
PROBLEM http://127.0.0.1:8097/ answered HTTP 000 (failed 2 run(s) in a row)
The second failure confirms the problem. One message reports both failed checks together, so a single incident does not lead to a flood of separate messages.
Run 4: Still Failing
A fourth run, with the server still down, prints the same [FAIL] lines, but the alert log still contains exactly one alert (grep -c ALERT alerts.log prints 1). The state file of the port check shows the reason:
$ cat st/port_127.0.0.1_8097
3 1
Three failed runs in a row, and the alert has already been sent. The script stays silent until something changes.
Run 5: Recovery
After the server is started again:
$ ./healthcheck.sh -q -s st -a ./notify.sh checks.conf; echo "status $?"
status 0
$ tail -6 alerts.log
Host: vm
Time: 2026-12-02 17:44:51
RECOVERED 127.0.0.1:8097 accepts connections
RECOVERED http://127.0.0.1:8097/ answered HTTP 200
With -q the passing checks are not printed, so the run produced no output at all, but the recovery message was delivered through the alert program. The next quiet run is silent, because no state has changed.
Printing the Alert and Stricter Settings
Without -a, the alert goes to standard output. With -n 1, an alert is sent at the first failure. The test file uses a limit that cannot be met and a program that does not exist:
$ printf 'disk / 10\nprocess no-such-daemon\n' > bad.conf
$ ./healthcheck.sh -n 1 -s st2 bad.conf; echo "status $?"
[FAIL] disk / is 29% full (limit 10%)
[FAIL] process process no-such-daemon is NOT running
Health check on vm: 2 change(s)
Host: vm
Time: 2026-12-02 17:44:51
PROBLEM / is 29% full (limit 10%) (failed 1 run(s) in a row)
PROBLEM process no-such-daemon is NOT running (failed 1 run(s) in a row)
status 1
Input Errors
$ ./healthcheck.sh
healthcheck.sh: give exactly one check file (try -h)
$ ./healthcheck.sh -n 0 x
healthcheck.sh: -n needs a whole number of at least 1
$ ./healthcheck.sh nofile
healthcheck.sh: cannot read nofile
$ printf 'cpu 5\n' > e.conf; ./healthcheck.sh -s st3 e.conf
healthcheck.sh: unknown check 'cpu' in e.conf
$ printf '# only comments\n' > e2.conf; ./healthcheck.sh -s st3 e2.conf
healthcheck.sh: e2.conf contains no checks
$ ./healthcheck.sh -a nonexist checks.conf
healthcheck.sh: alert command not found: nonexist
All of these exit with status 2. A check file with no checks is an error on purpose: a monitor that silently checks nothing looks the same as a healthy server.
Scheduling the Health Check
Run it every minute from cron (lesson 170), with the alert delivered by your notification script (lesson 173). The state directory must be writable by the user who runs the job and should survive between runs, which is why the default is /var/tmp and not /tmp:
* * * * * /usr/local/bin/healthcheck.sh -q -n 3 -a "/usr/local/bin/notify.sh" /etc/healthcheck/checks.conf
With a one-minute interval and -n 3, a problem is reported when it has lasted at least three minutes. For the check of a critical service, use a smaller number. For the file system and the load, which change slowly, a larger number reduces noise. To prevent two runs from overlapping on a slow system, combine the job with a lock (lesson 171):
* * * * * flock -n /var/lock/healthcheck.lock /usr/local/bin/healthcheck.sh -q -a /usr/local/bin/notify.sh /etc/healthcheck/checks.conf
Ideas for Extending the Project
- Alert levels. Add a second, higher limit for each check, for example "warning at 80%, critical at 95%", and include the level in the message.
- Reminders. Store the time of the alert in the state file and send a reminder every few hours while the problem continues.
- Certificate expiry. Add a
cert HOST DAYScheck that usesopenssl s_clientandopenssl x509 -enddateto warn before a TLS certificate runs out. - Service managers. Add a
service NAMEcheck based onsystemctl is-active --quiet NAMEfor systems that run systemd. - Machine-readable output. Add a
-o jsonmode, so that a dashboard can show the latest state of all checks.