Interview Prep/Shell Scripting/Scenarios: backups, log rotation and housekeeping

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
  1. Files are processed newest first, so the first file seen in each week or month is the newest one.
  2. Run it with a --dry-run that 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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: backups, log rotation and housekeeping