Intermediate · 25 min · practise every command in the built-in terminal

🛠 Project: Uptime Monitor

The café runs a few websites, and the owner finds out a site is down when a customer calls. Your job: a script that checks every site every 5 minutes and writes down which ones are failing. The sites to watch are in ~/monitor/sites.txt, one address per line.

What the script has to do

  1. For each address in ~/monitor/sites.txt, print UP or DOWN, the status code and the address
  2. A site is up when the code is 200–399. A missing page (404), an error (500) or no answer at all (000) counts as down
  3. Add every down site to ~/logs/uptime.log, with the date and time
  4. Exit with status 1 when anything is down
  5. Run every 5 minutes, from cron

Building blocks

curl -s -o /dev/null -w '%{http_code}' http://shop.test   # Just the status code: 200
curl -s -o /dev/null -w '%{http_code}' http://api.test:8080/health   # 000: nothing answered
while read url; do echo "checking $url"; done < ~/monitor/sites.txt   # One line at a time
code=$(curl -s -o /dev/null -w '%{http_code}' "$url")
if [ "$code" -ge 200 ] && [ "$code" -lt 400 ]; then echo up; fi
date '+%F %T'

💡 -s keeps curl quiet, -o /dev/null throws the page away, and -w '%{http_code}' prints only the code. That's the classic way to check a site from a script.

Practice tasks

  1. Ask http://shop.test for nothing but its status code
  2. Create ~/scripts/uptime.sh, a bash script, and make it executable
  3. Run it: it prints UP or DOWN for every site in ~/monitor/sites.txt
  4. The down sites are in ~/logs/uptime.log, with the date and time
  5. It exits with status 1 when a site is down
  6. Make it run every 5 minutes

Commands in this lesson

Projects