Implement retention of 7 daily, 4 weekly and 12 monthly backups (GFS) in a script.
AdvancedScenarioScenarios: backups, log rotation and housekeeping
Answer
Situation read → Classify each backup by date, keep the newest in each bucket, delete the rest.
What I'd do →
declare -A keep=()
mapfile -t files < <(find "$dir" -maxdepth 1 -name "$host-*.tar.gz" -printf '%f\n' | sort -r)
daily=0; declare -A seen_w seen_m
for f in "${files[@]}"; do
d=${f#"$host-"}; d=${d:0:8} # YYYYMMDD from the name
if (( daily < 7 )); then keep[$f]=1; daily=$((daily + 1)); fi
w=$(date -d "$d" +%G-W%V); m=${d:0:6}
if [[ -z ${seen_w[$w]:-} ]] && (( ${#seen_w[@]} < 4 )); then seen_w[$w]=1; keep[$f]=1; fi
if [[ -z ${seen_m[$m]:-} ]] && (( ${#seen_m[@]} < 12 )); then seen_m[$m]=1; keep[$f]=1; fi
done
for f in "${files[@]}"; do [[ -n ${keep[$f]:-} ]] || rm -f -- "$dir/$f" "$dir/$f.sha256"; done
- Files are processed newest first, so the first file seen in each week or month is the newest one.
- Run it with a
--dry-runthat prints decisions before enabling deletion.
Why → GFS gives fine recent granularity and long history with few files.
Interview tip → Mention that for S3, tools like restic (forget --keep-daily 7 --keep-weekly 4 --keep-monthly 12) or lifecycle tiers do this without custom code.
More on Scenarios: backups, log rotation and housekeeping
Design a nightly backup of `/etc` and application data to S3 with retention.IntermediateWrite the core of a Postgres backup that streams `pg_dump` through gzip to S3 and never uploads an empty dump.IntermediateBackups have "succeeded" every night for a year, but the first real restore failed. How do you make backups trustworthy?Advanced`/var` is 100% full because an app's logs were never rotated, and the app now fails to start. What do you do now, and what do you set up after?BeginnerShould you use `copytruncate` or a `postrotate` signal for an application's logs? How do you decide?Intermediate`/srv/app/releases` has 300 old release directories. Write a cleanup that keeps the newest 5 and never deletes the current release.Beginner