In this lesson, you will learn how to design a self-pruning backup system that intelligently manages your storage footprint using systemd timers and custom logic.
When automating backups, simply running a script is not enough; you must implement a "retention policy" to ensure old data is discarded, preventing disk exhaustion. While simple scripts might delete everything older than seven days, a robust system—often called Grandfather-Father-Son (GFS) rotation—requires more nuanced logic.
Building the Retention Logic
Instead of relying on basic file system mtimes, we build a logic block within a shell script triggered by a systemd timer. This script evaluates the directory structure and applies retention rules:
#!/bin/bash
# /usr/local/bin/rotate-backups.sh
BACKUP_DIR="/mnt/backups"
# Keep daily backups for 7 days
find "$BACKUP_DIR" -name "daily-*.tar.gz" -mtime +7 -exec rm {} \;
# Keep weekly backups for 4 weeks
find "$BACKUP_DIR" -name "weekly-*.tar.gz" -mtime +28 -exec rm {} \;
# Keep monthly backups for 6 months
find "$BACKUP_DIR" -name "monthly-*.tar.gz" -mtime +180 -exec rm {} \;
Orchestrating with Systemd
You trigger this logic using a standard systemd timer unit. By separating the backup generation from the pruning logic, you can schedule the rotation to run immediately after the backup finishes, or at a separate off-peak hour to avoid I/O contention.
When designing this, ensure your script handles empty states or partial backups gracefully. It is a best practice to use ExecStartPre in your backup unit to verify that your storage threshold isn't already exceeded before initiating a new write operation. By coupling systemd timers with specific find criteria, you create a "self-cleaning" infrastructure that scales with your storage needs.
This approach prevents the common pitfall of "backup bloat," where automated processes silently consume all available space until the system becomes unresponsive. Always test your retention logic by creating mock files in a staging directory first to ensure your find parameters behave exactly as expected before deploying to production storage.
Key Takeaway: Effective backup rotation relies on decoupling the archival task from the pruning logic, using scheduled timers to enforce specific retention windows that prevent disk exhaustion.