Ravindra BagaleCourses & study guides Track your progress

Labs · DevOps

Lab: Write a Bash Health-Check Script for Disk, Memory and a Web Port, Add a Dry-Run Mode and Schedule It with cron

Beginner40 minLinux or WSL or a Mac Terminal · bash · curl · cron

Course: DevOps · Chapter 5: Bash Scripting for Automation · Lesson: 5.11 Lab: health-check script with dry run

Chapter 5 explains variables, if, loops, exit codes and cron; this lab puts them in one useful script.

Chala mitrano! Roj sakali tech dahaa commands haatane chalavto na? Aaj tyacha ek script banvuya ani cron la deuya.

Suppose we are…

Suppose we are on the night support team for a Netflix-style streaming app. Every morning someone logs in and types the same ten commands: is the disk full, is memory OK, does the web port answer? Humans forget steps at 6 a.m. A script does not.

In this lab we write one small health-check script with clear exit codes, a --dry-run mode that only prints what it would do, and a cron entry that runs it every five minutes and writes a log.

Goal of this lab

By the end you will have:

  • A script health.sh that checks disk, memory and one HTTP URL.
  • Exit code 0 when healthy and 1 when something is wrong.
  • A --dry-run flag and a cron job writing to a log file.

What you need

  • A Linux machine, WSL on Windows, or a Mac (on a Mac, the memory check is skipped).
  • curl installed.
  • 40 minutes.

Part 1: Write the script

  1. Create a folder and the script file:

    mkdir -p ~/ops && cd ~/ops
    nano health.sh
    
  2. Paste this script and save it:

    #!/usr/bin/env bash
    # health.sh - disk, memory and web checks. Usage: ./health.sh [--dry-run] [url]
    set -u
    
    DRY_RUN=false
    if [ "${1:-}" = "--dry-run" ]; then DRY_RUN=true; shift; fi
    URL="${1:-http://localhost:80}"
    DISK_LIMIT=80     # percent
    MEM_LIMIT=90      # percent
    status=0
    
    log() { echo "$(date '+%F %T') $*"; }
    
    run() {
      if $DRY_RUN; then log "DRY-RUN would run: $*"; return 0; fi
      "$@"
    }
    
    # 1. Disk usage of /
    disk=$(df -P / | awk 'NR==2 {gsub("%","",$5); print $5}')
    if [ "$disk" -ge "$DISK_LIMIT" ]; then log "FAIL disk ${disk}% (limit ${DISK_LIMIT}%)"; status=1; else log "OK   disk ${disk}%"; fi
    
    # 2. Memory (Linux only)
    if command -v free >/dev/null 2>&1; then
      mem=$(free | awk '/Mem:/ {printf "%d", ($2-$7)*100/$2}')
      if [ "$mem" -ge "$MEM_LIMIT" ]; then log "FAIL memory ${mem}%"; status=1; else log "OK   memory ${mem}%"; fi
    else
      log "SKIP memory (free not found)"
    fi
    
    # 3. Web check
    if run curl -fsS -o /dev/null --max-time 5 "$URL"; then log "OK   web $URL"; else log "FAIL web $URL"; status=1; fi
    
    exit $status
    
  3. Make it executable for your user and group only, with no write access for anyone else:

    chmod 750 health.sh
    ls -l health.sh
    

    What you should see: -rwxr-x--- at the start of the line.

Part 2: Run it three ways

  1. Dry run first. Nothing is called; you see what would happen:

    ./health.sh --dry-run https://example.com
    

    What you should see: DRY-RUN would run: curl -fsS ... plus the disk and memory lines.

  2. Real run against a working site, then read the exit code:

    ./health.sh https://example.com; echo "exit=$?"
    

    What you should see: three OK lines and exit=0.

  3. Real run against a port where nothing listens:

    ./health.sh http://localhost:9; echo "exit=$?"
    

    What you should see: FAIL web http://localhost:9 and exit=1.

Part 3: Schedule it with cron

  1. Open your crontab:

    crontab -e
    
  2. Add this line (use your own home path), save and close:

    */5 * * * * /home/YOURUSER/ops/health.sh https://example.com >> /home/YOURUSER/ops/health.log 2>&1
    

    */5 * * * * means every 5 minutes. >> appends to the log and 2>&1 also catches errors.

  3. Check the entry and wait 5 minutes:

    crontab -l
    tail -n 5 ~/ops/health.log
    

    What you should see: new timestamped OK lines every 5 minutes.

Clean up

  1. Remove the cron line when you are done practising:

    crontab -e    # delete the health.sh line, save
    crontab -l
    

    What you should see: the line is gone.

Ravindra Bagale's Tip

Every script that changes something should have a dry run. Run it in dry mode first, read the output, and only then run it for real.

Common mistakes

MistakeWhat happensFix
Windows line endings in the script/usr/bin/env: 'bash\r': No such fileRun sed -i 's/\r$//' health.sh or save with LF endings
Relative paths inside cronWorks by hand, fails in cronUse full paths in the crontab line
Giving everyone write access to "fix" permission deniedAnyone on the server can edit your scriptUse chmod 750 or 700
Forgetting exit $statusAlways exits 0, monitoring never sees failuresEnd the script with the collected status

Self-check checklist

0 of 4 done

Try-at-home challenge

Add a fourth check: warn if the service nginx is not active (systemctl is-active --quiet nginx). Make the disk limit a command-line option such as --disk-limit 70.

Samajla ka? Script once, cron forever, and dry run before real run. Aata pudhe jaauya Docker kade.