A cleanup script must delete files older than 14 days in `/data/exports`, but someone once deleted `/` by mistake with a similar script. How do you write it safely?
IntermediateScenarioScheduling, automation and scripting
Answer
Situation read → Guard against empty variables and wrong paths.
What I'd do →
#!/usr/bin/env bash
set -euo pipefail
target="${EXPORT_DIR:?EXPORT_DIR not set}"
[[ "$target" == /data/exports* ]] || { echo "refusing: $target"; exit 1; }
find "$target" -xdev -type f -mtime +14 -print -delete
Run once with -print only (no -delete) to review.
Why → ${VAR:?} aborts if empty, so rm -rf "$VAR/" can never become rm -rf /. -xdev stops find crossing into other mounts.
Interview tip → Mention the famous Steam bug (rm -rf "$STEAMROOT/"* with an empty variable).
More on Scheduling, automation and scripting
A database dump must run every night at 1:30 AM. How do you schedule it with cron so it is reliable?BeginnerConvert that nightly cron job to a systemd timer. Why would you?IntermediateA cron job runs every 5 minutes, but sometimes takes 8 minutes and two copies overlap, corrupting data. How do you prevent that?BeginnerYou have 300 servers running the same cron job at midnight, and they hammer a shared API. How do you fix it?IntermediateA job must run on the last day of every month. Cron has no "last day" field. What do you do?IntermediateYou inherited a server and need to know every scheduled job on it. Where do you look?Beginner