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

`/srv/app/releases` has 300 old release directories. Write a cleanup that keeps the newest 5 and never deletes the current release.

BeginnerScenarioScenarios: backups, log rotation and housekeeping
Answer

Situation read → Sort by name if names are timestamps, and protect the directory current points to.

What I'd do →

releases=/srv/app/releases
current=$(readlink -f /srv/app/current)
mapfile -t old < <(find "$releases" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort -r | tail -n +6)
for r in "${old[@]}"; do
  [[ "$releases/$r" == "$current" ]] && continue
  rm -rf -- "${releases:?}/$r"
  echo "removed $r"
done
  1. Release names like 20261109T143000Z sort chronologically as strings.
  2. ${releases:?} guards against an empty variable.

Why → Keeping a few releases enables instant rollback; deleting the live one would cause an outage.

Interview tip → Mention that sorting by name is more reliable than by mtime, which changes when someone touches a file.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: backups, log rotation and housekeeping