Menu
CoddyTech

Backup Rotator

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 39 of 39.

challenge icon

Challenge

Hard

Write rotate.sh, which keeps the newest backups in a folder and deletes the older ones.

  1. The script takes two arguments: a folder and N, the number of backups to keep. With any other number of arguments, print Usage: rotate.sh DIR N to stderr and exit 1.
  2. When DIR is not a folder, print Error: DIR is not a folder to stderr, with the argument in place of DIR, and exit 2. When N is not made of digits only, print Error: N must be a whole number to stderr and exit 1.
  3. A backup is a file named backup-YYYY-MM-DD.tar.gz, with a four-digit year, a two-digit month and a two-digit day. Leave every other file alone, also backup-old.tar.gz.
  4. The date in the name decides the age. Keep the N newest backups and delete the rest, oldest first, printing Removed NAME for each one, without the folder.
  5. Last, print Kept K, removed R with the two counts. When there are N backups or fewer, nothing is removed.

Try it: backups holds five dated backups from 2025-12-27 to 2026-01-24. Run bash rotate.sh backups 3. It prints:

Removed backup-2025-12-27.tar.gz
Removed backup-2026-01-03.tar.gz
Kept 3, removed 2

Then ls backups lists:

backup-2026-01-10.tar.gz
backup-2026-01-17.tar.gz
backup-2026-01-24.tar.gz
backup-old.tar.gz
notes.txt

A count that is not a number fails:

bash rotate.sh backups two 2>&1; echo "exit $?"
Error: N must be a whole number
exit 1

Try it yourself

Terminal

All lessons in Bash Scripting

Practice on your own: Terminal playground