Schedule a cleanup job that logs what it did and fails loudly

short · 45 min · Objective 2.6

Task

Turn a cleanup task into a scheduled job that runs unattended: delete files older than seven days from one explicit folder, log every deletion with a timestamp, exit non-zero if the folder is missing, and run from cron. Then break it on purpose and confirm the failure is visible without anyone watching.

Steps

  1. Create /srv/scratch with twenty files, and use touch -d '10 days ago' on ten of them.
  2. Write /usr/local/bin/cleanup-scratch.sh with set -eu, a fixed target path (never built from an empty variable), a check that exits with status 2 and a message on standard error saying the folder does not exist, and find with -mtime +7 -print -delete, appending each deleted path with a timestamp to /var/log/cleanup-scratch.log. Copy it to lab/automate/cleanup-scratch.sh.
  3. Add a crontab entry that runs it every five minutes, redirecting any error output to the log as well. Save crontab -l to lab/automate/crontab.txt.
  4. After it has run, copy the log to lab/automate/run-ok.log and save ls /srv/scratch | wc -l to lab/automate/remaining.txt.
  5. Rename /srv/scratch so the folder is missing, wait for the next run, and copy the log to lab/automate/run-fail.log. Rename it back.

Verify

These checks run in a POSIX shell: Terminal on macOS or Linux, and on Windows Git Bash (it comes with Git for Windows) or WSL. A stock Windows PowerShell or Command Prompt has no awk or grep, so there the first line fails.

grep -c 'set -eu' lab/automate/cleanup-scratch.sh
grep -Ec 'exit 2' lab/automate/cleanup-scratch.sh
grep -Ec '^[*/0-9,-]+[[:space:]]' lab/automate/crontab.txt
grep -c '/srv/scratch/' lab/automate/run-ok.log
cat lab/automate/remaining.txt
grep -Eic 'missing|not exist|no such' lab/automate/run-fail.log

Ten deletions are logged, ten files remain, and the failure run left a message in the log. A job that failed silently when its folder disappeared would look exactly like a job with nothing to delete -- the difference only exists because the script says so.

Notes

A systemd timer does the same job with the output going to the journal automatically, and its Persistent=true setting runs a missed job after a server was off at the scheduled time, which cron does not.

This is an independent study companion for CompTIA Server+ SK0-005 and is not produced by or endorsed by CompTIA.