Capstone: Automate a Server Health Check in Bash
Every morning you log in to a server, run df, free and uptime, and open the home page to see that it loads. On a busy day you skip it, and that is the day the disk fills up. This capstone builds a server health check in Bash: a script that takes the same measurements every time, flags anything out of range, logs the result and runs every 10 minutes.
Plan the check-up: five measurements
Pick measurements that each catch a common failure with one command. A threshold is the limit past which a check says WARN:
| Check | Command | WARN when |
|---|---|---|
| Disk | df -P / | more than 80% full |
| Memory | free -m | under 10% available |
| Load | uptime | 5-minute load at or above the core count |
| Service | systemctl is-active | not active |
| Web | curl | status not 200 |
Memory uses available, not free, because Linux lends spare RAM to the page cache (lesson 14). Load compares the 5-minute average, which smooths out short bursts, with the core count from nproc.
A service that systemd reports as active (lesson 12) can still fail to answer, so the web check also fetches a page with curl (curl for beginners) and expects status code 200, which means OK (what is HTTP).
In the flowchart, notice that a WARN does not stop the run: every measurement comes first, then the decision.
One function per check
A function is a named group of commands inside a script, run by typing its name. Each check is one: it measures, compares, prints one line and ends with return, which sets the function's exit code: 0 for OK, 1 for WARN. local makes a variable that exists only inside the function.
Here is the disk check; log, explained below, prints and saves a line:
check_disk() {
local used
# field 5 of df -P is the percent used, such as 41%
used=$(df -P "$DISK_PATH" | awk 'NR == 2 { sub(/%/, "", $5); print $5 }')
if [[ -z "$used" ]]; then
log "WARN disk: cannot read $DISK_PATH"
return 1
elif [[ $used -gt $DISK_MAX ]]; then
log "WARN disk: $DISK_PATH is $used% full (limit $DISK_MAX%)"
return 1
fi
log "OK disk: $DISK_PATH is $used% full (limit $DISK_MAX%)"
return 0
}
df -P prints the portable (POSIX) format, one unwrapped line per filesystem. In awk (lesson 9), NR == 2 picks the line after the header and sub() deletes the % sign. If df fails, say because DISK_PATH has a typo, used stays empty and the first test makes that a WARN.
The other checks have the same shape. Memory divides the available column of free -m by total, as a percent. Load takes the 5-minute figure from uptime and compares ${load%.*}, the value with its decimals cut off, because Bash compares only whole numbers; with a whole-number limit, the answer is the same.
The service check prints SKIP if /run/systemd/system is missing, which means systemd is not running the machine, as in a container. Otherwise systemctl is-active --quiet returns 0 only for an active service. The web check runs curl with --write-out '%{http_code}' to print just the status code; 000 means no answer at all.
Thresholds at the top, a summary and an exit code
Values you will tune belong in capitalised variables at the top, so another server needs only new values. After its comments, the lab's script starts like this:
set -euo pipefail
export LC_ALL=C # numbers with a dot: 0.52, not 0,52
# ----- Settings: change these -----
DISK_PATH="/" # the filesystem to check
DISK_MAX=80 # WARN above this % used
MEM_MIN=10 # WARN below this % available
LOAD_MAX=$(nproc) # WARN at this 5-minute load (a whole number)
SERVICE="nginx" # a systemd service that must be active
URL="http://web/" # a page that must answer 200
LOG_FILE="/tmp/health-check.log" # every line is also appended here
LC_ALL=C picks the plain default language settings, so uptime never writes a decimal comma. URL is the lab's web container; on a server, use your own page, such as http://localhost/. The main part runs every check, and || (lesson 16) adds 1 to warnings whenever one returns 1, then lets the run continue:
warnings=0
check_disk || warnings=$((warnings + 1))
check_memory || warnings=$((warnings + 1))
check_load || warnings=$((warnings + 1))
check_service || warnings=$((warnings + 1))
check_url || warnings=$((warnings + 1))
if [[ $warnings -gt 0 ]]; then
log "SUMMARY: $warnings WARN, exit code 1"
exit 1
fi
log "SUMMARY: 0 WARN, exit code 0"
exit 0
The exit code lets other programs react without reading any text, as in ./health-check.sh || echo "look at web1". Here is an illustrative server run with one WARN:
Log every run and schedule it every 10 minutes
The log function is one line, echo "$(date '+%F %T') $1" | tee -a "$LOG_FILE": date prints the date and time, and tee -a copies each line to the screen and also appends it to LOG_FILE. On a server, set LOG_FILE to /var/log/health-check.log, a file an admin creates once with sudo touch and sudo chown, as in lesson 18. Then add this line with crontab -e:
*/10 * * * * /home/anita/health-check.sh > /dev/null 2>> /var/log/health-check.log
*/10 means minutes 0, 10, 20 and so on. tee already writes the log, so > /dev/null drops the screen copy, while 2>> appends any error to the same file. Those error lines carry no date, as they skip log. Every command the script uses is in /usr/bin or /bin, inside cron's minimal PATH.
In the diagram, notice the dashed box: nothing reads the exit code yet.
Make it safe, then make it useful
set -euo pipefail (lesson 16) stops the script at a failed command, an unset variable such as a misspelled $DISK_MXA, or a failed pipeline. One hole matters here: inside a function called on the left of ||, Bash switches set -e off, which is why each check tests its own result. Quoted variables, such as "$URL", stay one argument even with a space (lesson 17).
Next, add an alert, because cron ignores the exit code. End the crontab line with || and a command that sends an email with mail, which needs the mail system from lesson 18, or uses curl to post to a chat tool's incoming webhook, a web address that turns a request into a message. Alert only on what needs a person (alerting best practices).
Check yourself
The web line says answered 000, and later answered 502. What is the difference?
000 means no HTTP answer at all: nothing listened, the name did not resolve, or 5 seconds passed. 502 means a web server answered with an error status, so the network works and the fault lies behind that server.
cron has run the check all week, and it has exited 1 since Tuesday. Who found out?
Nobody, unless someone read the log. cron ignores exit codes; only an alert after || turns that 1 into a message.
The script has set -e, so why does check_disk still test for an empty value?
It runs on the left of ||, where set -e is off inside the function. A failed df leaves used empty, which Bash compares as 0, a false OK; the test turns it into a WARN.