How to Automate Old Backup Deletion

Why Delete Old Backups?

by Dharmesh Patel

Managing backups is crucial for maintaining system health, but over time, old backups can accumulate, taking up valuable storage space and potentially slowing down your system. Automating backup deletion ensures that only recent, relevant backups are retained, preventing this clutter and freeing up space for new files. This article shows how to automate the deletion of backups older than X days while keeping only the most recent ones.

Steps to Set Up Backup Deletion

To automate backup deletion and retain only the last X days of files, you can set up a cron job that runs a script to delete older backups while keeping only the most recent ones.

1. Create a Script to Delete Old Backups

The first step is to write a bash script that will identify and delete backups older than your specified retention period (X days). Below is a sample bash script:

Styled Code Snippet
# Define the backup directory
BACKUP_DIR="/path/to/your/backups"

# Define the retention period (in days) RETENTION_DAYS=7
# Find and delete backups older than the retention period find "$BACKUP_DIR" -type f -mtime +$RETENTION_DAYS -exec rm -f {} \;
echo "Old backups older than $RETENTION_DAYS days have been deleted."

In this script, we:

  • Set the path to the backup directory.
  • Define how many days of backups to retain (RETENTION_DAYS).
  • Use the find command to search for backups older than the defined period and delete them.
2. Schedule the Script with Cron

Now that the script is ready, it's time to automate its execution using cron. A cron job will run this script at a specified interval (e.g., daily), ensuring that your backups are cleaned up regularly.

  • To edit your cron jobs, open the crontab:
crontab -e
  • Then, add an entry to run the script daily (or adjust the time as needed). For example, to run the script every day at midnight:
0 0 * * * /path/to/your/script.sh

This cron job will execute the script every day at midnight, ensuring that only the backups from the last 7 days are retained.

3. Test the Script

It’s important to test the script manually to ensure it works as expected. Run the following command:

bash /path/to/your/script.sh

This will help confirm that backups older than the defined period (e.g., 7 days) are deleted successfully.

In Summary

By automating the deletion of old backups, you ensure that your storage remains organised and that your system has enough room for new data without manually deleting old files. This simple cron job can be tailored to your specific needs and adjusted for different retention periods or backup schedules.

Need more development tips?

Stay tuned to our blog.

Understanding the await Function in Flutter