Schedule a cleanup job that logs what it did and fails loudly
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
- Create
/srv/scratchwith twenty files, and usetouch -d '10 days ago'on ten of them. - Write
/usr/local/bin/cleanup-scratch.shwithset -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, andfindwith-mtime +7 -print -delete, appending each deleted path with a timestamp to/var/log/cleanup-scratch.log. Copy it tolab/automate/cleanup-scratch.sh. - Add a crontab entry that runs it every five minutes, redirecting any error output to the log as well. Save
crontab -ltolab/automate/crontab.txt. - After it has run, copy the log to
lab/automate/run-ok.logand savels /srv/scratch | wc -ltolab/automate/remaining.txt. - Rename
/srv/scratchso the folder is missing, wait for the next run, and copy the log tolab/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.