Course contents · Lesson 19 of 19

Capstone: Automate a Server Health Check in Bash

Shell Scripting · Lesson 19 of 19 · 12 min Hands-on

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:

CheckCommandWARN when
Diskdf -P /more than 80% full
Memoryfree -munder 10% available
Loaduptime5-minute load at or above the core count
Servicesystemctl is-activenot active
Webcurlstatus 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.

Flowchart of one run of health-check.sh. Start: cron or you run it. Five checks run in order: 1 disk with df -P, 2 memory with free -m, 3 load with uptime, 4 service with systemctl is-active, 5 web with curl on the URL. Each reads its threshold from the top of the script: DISK_MAX=80, MEM_MIN=10, LOAD_MAX=$(nproc), SERVICE=nginx and URL=http://web/. Each prints one line: OK and return 0, WARN and return 1, or SKIP and return 0 when there is no systemd. A WARN adds 1 to warnings and the next check runs anyway. Then: any WARN, warnings greater than 0? Yes: log SUMMARY: 1 WARN and exit 1. No: log SUMMARY: 0 WARN and exit 0. Each line also lands in LOG_FILE with the date and time
All five checks always run; only at the end does one question decide the exit code.

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:

A terminal on a server called web1, with illustrative numbers. anita runs ./health-check.sh, and each line starts with the date and time 2026-12-02 10:20:01. WARN disk: / is 91% full (limit 80%), marked over DISK_MAX. OK memory: 64% available (minimum 10%). OK load: 1.20 over 5 minutes (limit 4). OK service: nginx is active. OK web: http://localhost/ answered 200. These are marked one line per check, in the same order. Then SUMMARY: 1 WARN, exit code 1, marked as counting the WARN lines. echo $? then prints 1, marked not all clear. A footer says each line also goes to the log file
The lines tell a person what is wrong; the exit code tells a program that something is.

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.

Architecture. cron, with the schedule */10 * * * *, starts health-check.sh every 10 minutes. The script holds the thresholds at the top and five check functions, and runs each check: disk with df -P, memory with free -m, load with uptime, service with systemctl and web with curl. Each returns 0 for OK and 1 for WARN. With tee -a the script appends its lines to the log file /var/log/health-check.log, and it ends with an exit code: 0 when all is OK, 1 for a WARN. A dashed arrow, not built yet, leads from the exit code to the next step: an alert by email or chat message. A footer says cron does not read the exit code, so an alert must
cron only starts the script; the log and the exit code are its two results.

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.