Why Delete Old Backups?
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:
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:
- 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:
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:
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.