Backup Rotator
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 39 of 39.
Challenge
HardWrite rotate.sh, which keeps the newest backups in a folder and deletes the older ones.
- 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 Nto stderr and exit1. - When DIR is not a folder, print
Error: DIR is not a folderto stderr, with the argument in place of DIR, and exit2. When N is not made of digits only, printError: N must be a whole numberto stderr and exit1. - 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, alsobackup-old.tar.gz. - The date in the name decides the age. Keep the N newest backups and delete the rest, oldest first, printing
Removed NAMEfor each one, without the folder. - Last, print
Kept K, removed Rwith 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 2Then 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.txtA count that is not a number fails:
bash rotate.sh backups two 2>&1; echo "exit $?"
Error: N must be a whole number
exit 1Try it yourself
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground