Skip to content
$ lynuxpro
← Bash Scripting

LESSON 14 OF 17 · ADVANCED · 25 MIN

Automation project: health check and backup

HOW IT WORKSProject: health check and backup

OPS.SHruncron 02:00triggercheck diskdf, alert > 85%
1/5

cron starts one script nightly. Strict mode, a lock and a trap make it safe to run unattended.

exec 9>/tmp/ops.lock; flock -n 9 || exit 0

Time to put everything together. In this project you build ops.sh, a production-style maintenance script of the kind that runs on thousands of real servers. Every night it checks the server's health, alerts if something is wrong, backs up important configuration, verifies the backup and deletes old ones. You will use variables, conditionals, loops, functions, arrays, text processing, strict mode, traps, locking, options and scheduling — every lesson so far.

In simple words

  • Health check: a script that tests whether a server or service is working and reports problems.
  • Backup script: a script that copies important data somewhere safe on a schedule and cleans up old copies.
  • Idempotent: safe to run many times: running it again gives the same result without harm.

Requirements

Before writing code, write down what the script must do. This is how real automation starts:

  1. Health checks
    • Disk: warn when any filesystem is above a threshold (default 85%).
    • Memory: warn when available memory is below 10%.
    • Services: each service in a list must be active.
    • HTTP endpoints: each URL must return status 200.
  2. Backup
    • Archive a list of paths into /backup/NAME-YYYY-MM-DD.tar.gz.
    • Record a SHA-256 checksum next to the archive.
    • Delete archives older than N days (default 7).
  3. Operations
    • Options: -c checks only, -b backup only, -n dry run, -v verbose, -h help.
    • Log with timestamps; send a Slack alert when any check fails.
    • Never run twice at once; clean up temp files on any exit.
    • Exit code = number of failed checks (0 means healthy), so cron, systemd or a monitoring agent can react.

Building the pieces

Try each piece in the practice terminal before assembling the script.

Disk usage

df -P prints POSIX-format output, one filesystem per line, with the usage percentage in column 5. awk filters it; $5+0 turns "28%" into the number 28:

df -Pdf -P | awk 'NR > 1 {print $6, $5}'df -P | awk -v max=85 'NR > 1 && $5+0 > max {print $6 " is at " $5}'df -P | awk -v max=20 'NR > 1 && $5+0 > max {print $6 " is at " $5}'
SHELLbashutf-8 · 4L
Filesystem      Size  Used Avail Use% Mounted on/dev/root        30G  8.2G   22G  28% /tmpfs           2.0G     0  2.0G   0% /dev/shm/ 28%/dev/shm 0%/ is at 28%
OUTPUTterminalutf-8 · 6L

With the real threshold nothing is printed, which means healthy. Lowering it to 20% shows what a warning looks like.

Memory

free -m shows memory in megabytes. The "available" column (7) is what applications can still use:

free -mfree -m | awk '/^Mem:/ {printf "%d%% available\n", $7 * 100 / $2}'
SHELLbashutf-8 · 2L
               total        used        free      shared  buff/cache   availableMem:            3936         912        2210          12         813        2780Swap:              0           0           070% available
OUTPUTterminalutf-8 · 4L

Services and endpoints

for svc in nginx cron ssh; do printf '%-8s %s\n' "$svc" "$(systemctl is-active "$svc")"; donecurl -s -o /dev/null -w "%{http_code}" https://example.com
SHELLbashutf-8 · 2L
nginx    activecron     activessh      active200
OUTPUTterminalutf-8 · 4L

curl -o /dev/null -w "%{http_code}" throws the body away and prints only the status code, which is easy to compare.

Backup, checksum and rotation

day=$(date +%F)tar -czf "/backup/etc-$day.tar.gz" /etc/hosts /etc/nginxtar -tzf "/backup/etc-$day.tar.gz"sha256sum "/backup/etc-$day.tar.gz" > "/backup/etc-$day.tar.gz.sha256"sha256sum -c "/backup/etc-$day.tar.gz.sha256"ls /backupfind /backup -name 'etc-*.tar.gz' -mtime +7find /backup -name 'etc-*.tar.gz' -mtime +7 -deletels /backup
SHELLbashutf-8 · 9L

tar -tzf lists the archive so you can see it contains what you expect. sha256sum -c re-reads the archive and compares it with the recorded checksum, which catches truncated or corrupted backups. find … -mtime +7 lists files older than seven days; add -delete only after you have checked the list.

The complete script

#!/usr/bin/env bash# ops.sh - nightly health check and config backupset -Eeuo pipefailexport PATH=/usr/local/bin:/usr/bin:/bin # ---------- settings (override with environment variables) ----------DISK_MAX=${DISK_MAX:-85}MEM_MIN=${MEM_MIN:-10}KEEP_DAYS=${KEEP_DAYS:-7}BACKUP_DIR=${BACKUP_DIR:-/backup}SLACK_WEBHOOK=${SLACK_WEBHOOK:-}SERVICES=(nginx cron ssh)URLS=(http://localhost/health)BACKUP_PATHS=(/etc/nginx /etc/hosts) # ---------- state ----------do_checks=1 do_backup=1 dry_run=0 verbose=0failures=0problems=() # ---------- helpers ----------log()  { printf '[%s] %s\n' "$(date '+%F %T')" "$*" >&2; }vlog() { (( verbose )) && log "$@" || true; }run()  { if (( dry_run )); then log "DRY RUN: $*"; else "$@"; fi; }fail() { problems+=("$*"); failures=$((failures + 1)); log "FAIL: $*"; } usage() {  cat <<EOFUsage: ${0##*/} [-c|-b] [-n] [-v] [-h]  -c   run health checks only  -b   run backup only  -n   dry run (no changes)  -v   verbose  -h   helpEnvironment: DISK_MAX=$DISK_MAX MEM_MIN=$MEM_MIN KEEP_DAYS=$KEEP_DAYS BACKUP_DIR=$BACKUP_DIREOF} alert() {  [[ -n $SLACK_WEBHOOK ]] || { vlog "no SLACK_WEBHOOK set, skipping alert"; return 0; }  local text="$(hostname): ${#problems[@]} problem(s): ${problems[*]}"  run curl -fsS -X POST -H 'Content-Type: application/json' \    -d "{\"text\": \"${text//\"/\\\"}\"}" "$SLACK_WEBHOOK" > /dev/null \    || log "could not send Slack alert"} # ---------- checks ----------check_disk() {  local line  while read -r line; do    fail "disk $line"  done < <(df -P | awk -v max="$DISK_MAX" 'NR > 1 && $5+0 > max {print $6 " at " $5}')  vlog "disk check done (max ${DISK_MAX}%)"} check_memory() {  local pct  pct=$(free -m | awk '/^Mem:/ {print int($7 * 100 / $2)}')  (( pct >= MEM_MIN )) || fail "memory only ${pct}% available"  vlog "memory ${pct}% available"} check_services() {  local svc  for svc in "${SERVICES[@]}"; do    systemctl is-active --quiet "$svc" || fail "service $svc is not active"  done} check_urls() {  local url code  for url in "${URLS[@]}"; do    code=$(curl -s -o /dev/null -m 5 -w '%{http_code}' "$url" || true)    [[ $code == 200 ]] || fail "$url returned ${code:-no response}"  done} # ---------- backup ----------backup() {  local day archive tmp  day=$(date +%F)  archive="$BACKUP_DIR/config-$day.tar.gz"  tmp=$(mktemp "$BACKUP_DIR/.config-XXXXXX")  TMP_FILES+=("$tmp")   log "backing up ${BACKUP_PATHS[*]} to $archive"  run tar -czf "$tmp" "${BACKUP_PATHS[@]}"  run mv "$tmp" "$archive"                       # atomic: never a half-written archive  run sh -c "sha256sum '$archive' > '$archive.sha256'"  run sha256sum -c --quiet "$archive.sha256" || fail "checksum failed for $archive"   local old  old=$(find "$BACKUP_DIR" -name 'config-*.tar.gz' -mtime +"$KEEP_DAYS" | wc -l)  run find "$BACKUP_DIR" -name 'config-*.tar.gz*' -mtime +"$KEEP_DAYS" -delete  log "removed $old backup(s) older than $KEEP_DAYS days"} # ---------- main ----------TMP_FILES=()cleanup() { (( ${#TMP_FILES[@]} )) && rm -f "${TMP_FILES[@]}"; return 0; }trap cleanup EXITtrap 'log "unexpected error at line $LINENO: $BASH_COMMAND"' ERR main() {  while getopts ":cbnvh" opt; do    case $opt in      c) do_backup=0 ;;      b) do_checks=0 ;;      n) dry_run=1 ;;      v) verbose=1 ;;      h) usage; exit 0 ;;      \?) usage >&2; exit 2 ;;    esac  done   exec 9> /var/lock/ops.lock  flock -n 9 || { log "another ops.sh is running, exiting"; exit 0; }   log "ops.sh starting (checks=$do_checks backup=$do_backup dry_run=$dry_run)"  if (( do_checks )); then    check_disk; check_memory; check_services; check_urls  fi  if (( do_backup )); then    mkdir -p "$BACKUP_DIR"    backup  fi   if (( failures )); then    alert    log "finished with $failures problem(s)"  else    log "all good"  fi  exit "$failures"} main "$@"
SHELLbashutf-8 · 137L

Walking through the design

  • Settings at the top, overridable from the environment (DISK_MAX=90 ./ops.sh), so the same script works on every server without edits.
  • Arrays for lists (services, URLs, paths): adding a service is a one-word change, and paths with spaces stay intact.
  • One function per check, each calling fail for problems instead of exiting, so a single run reports every problem, not just the first.
  • run wraps every change, so -n shows exactly what would happen. Use it before the first production run.
  • Atomic backup: tar writes to a temp file in the same folder, then mv renames it into place. A crash mid-write can never leave a broken archive with the real name, and the EXIT trap deletes the temp file.
  • Verification: a backup that cannot be read is worse than none, because you think you are safe. sha256sum -c proves the file is intact.
  • Locking with flock, so a slow run and the next scheduled run never overlap.
  • Exit code = number of failures: cron, systemd and monitoring agents can all act on it without parsing logs.
  • < <(df …) instead of df … | while: the loop runs in the main shell, so fail can update failures and problems.

Testing it safely

Always test in this order:

shellcheck ops.sh               # zero warningsbash -n ops.sh                  # parses./ops.sh -h                     # help works./ops.sh -c -v                  # checks only, verbose: nothing is changed./ops.sh -b -n -v               # backup in dry-run mode: see every commandDISK_MAX=1 ./ops.sh -c          # force a failure: does it alert and exit non-zero?sudo ./ops.sh                   # the real thingecho "exit code: $?"
OUTPUTterminalutf-8 · 8L

Forcing a failure (DISK_MAX=1) is important: an alert path you have never seen working probably does not work.

Scheduling it

As a systemd timer on a server:

# /etc/systemd/system/ops.service[Unit]Description=Nightly health check and config backup[Service]Type=oneshotExecStart=/opt/scripts/ops.shEnvironment=SLACK_WEBHOOK=https://hooks.slack.com/services/XXX# /etc/systemd/system/ops.timer[Timer]OnCalendar=*-*-* 02:30:00Persistent=trueRandomizedDelaySec=10m[Install]WantedBy=timers.target
OUTPUTterminalutf-8 · 17L

Or with cron:

30 2 * * * /opt/scripts/ops.sh >> /var/log/ops.log 2>&1
OUTPUTterminalutf-8 · 1L

Keep secrets like the webhook out of the script itself: in the unit's Environment= (or better, an EnvironmentFile= readable only by root), or a secrets manager.

Real-world scenario: what this kind of script catches

Teams that run scripts like this report the same catches again and again: a log folder slowly filling a disk weeks before it would have crashed the database; a service that failed to start after a kernel update and was silently down; an expired certificate making a health endpoint return 000; and, most valuable of all, backups that "succeeded" but were empty because a path had been renamed. The checksum and the "list the archive" habit turn that last one from a disaster during a restore into a Slack message the next morning.

When a fleet grows beyond a handful of servers, this logic usually moves into a configuration management tool (Ansible) and a monitoring system (Prometheus with alerting). The thinking — explicit checks, safe changes, verification, clear exit codes and alerts — stays exactly the same.

Extend it

  1. Add a check that warns when a TLS certificate expires within 14 days (openssl s_client and openssl x509 -enddate).
  2. Add a -k DAYS option to override KEEP_DAYS.
  3. Copy each new backup to object storage (aws s3 cp) and verify the upload.
  4. Add a heartbeat: ping a monitoring URL at the end of a fully successful run.
  5. Write the results as JSON (jq -n) so a dashboard can read them.

Cheat sheet

df -P | awk 'NR>1 && $5+0 > 85'            full filesystemsfree -m | awk '/^Mem:/ {print $7*100/$2}'  % memory availablesystemctl is-active --quiet svc            service checkcurl -s -o /dev/null -w '%{http_code}' u   HTTP status onlytar -czf a.tgz paths…   tar -tzf a.tgz     create / listsha256sum f > f.sha256; sha256sum -c f.sha256    verifyfind dir -name '*.tgz' -mtime +7 [-delete] rotationtmp=$(mktemp dir/.x-XXXX); …; mv "$tmp" final    atomic writeexec 9>/var/lock/x.lock; flock -n 9 || exit 0exit "$failures"                           exit code = problems
OUTPUTterminalutf-8 · 10L

Key takeaways

  • Start from written requirements, then build and test each piece on its own before assembling the script.
  • Report every problem in one run, alert on failures, and make the exit code meaningful.
  • Make changes safe: dry-run mode, atomic writes, verification and a lock.
  • Configure through environment variables and arrays so one script fits every server.
  • Test the failure path on purpose; an alert you have never seen fire probably does not work.