Course contentsShow
← Linux
Lesson 198 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Backup Rotation Logic

Implement intelligent retention policies for automated backup tasks.

In this lesson, you will learn how to implement automated retention policies to ensure your backup storage stays organized without manual intervention.

The Core Concept: Managing Storage Lifecycles

When you automate backups—perhaps by triggering a script via a systemd timer—your storage drive will eventually fill up if you never delete old files. Backup Rotation Logic is the strategy of keeping only the most relevant snapshots while discarding redundant or outdated ones.

A common industry standard is the "Grandfather-Father-Son" model, but for beginners, we often start with a simple "Daily-Weekly" rotation. The goal is to keep daily backups for the last week and weekly backups for the last month.

Implementing Logic in Bash

To automate this, your script needs to identify files based on their filesystem metadata, specifically their modification timestamps. You can use the find command to isolate and remove files older than a certain threshold.

Here is a simple example that keeps only the last 7 daily backup archives:

# Define the directory where backups are stored
BACKUP_DIR="/mnt/backups"

# Remove files older than 7 days in that directory
find "$BACKUP_DIR" -maxdepth 1 -name "backup-*.tar.gz" -type f -mtime +7 -delete

# Create a new backup
tar -czf "$BACKUP_DIR/backup-$(date +%F).tar.gz" /home/user/data

Why This Matters

In this script, the -mtime +7 flag tells Linux to look for files modified more than 7 days ago. By pairing this with -delete, you create an intelligent system that "self-cleans."

This is much safer than simply overwriting a single file, as it provides a buffer. If you accidentally corrupt your data or delete a file, you still have up to seven days of "history" to recover from. When designing your rotation, always ensure your script runs after the backup completes but before the storage hits capacity, keeping your archive directory clean and predictable.

Key Takeaway: Automating backup rotation ensures your storage remains available for new data by using filesystem metadata to prune old snapshots based on a predefined retention schedule.