Suppose you named the backup according to the date:
% date +%Y-%m-%d
2015-10-29
Then you can compute the date one year ago like this:
% date +%Y-%m-%d -d "-1 year"
2014-10-29
and the date 5 weeks ago like this:
% date +%Y-%m-%d -d "-5 weeks"
2015-09-24
So you can setup cronjobs with run every 3 months and every Sunday,
and delete backups that occurred one year ago and 5 weeks ago like this:
# Every 3 months, run the backup script
1 2 * */3 * /path/to/backup/script.sh > /path/to/backupdir/$(date +%Y-%m-%d-Q)
# Every 3 months, delete the backup made on that date the previous year
1 2 * */3 * /bin/rm /path/to/backupdir/$(date +%Y-%m-%d-Q -d "-1 year")
# Every Sunday, if backup does not exist, run backup script
1 3 * * 7 if [ ! -f /path/to/backupdir/$(date +%Y-%m-%d-Q) ]; then /path/to/backup/script.sh > /path/to/backupdir/$(date +%Y-%m-%d) fi
# Every Sunday, delete backup 5 weeks old
1 3 * * 7 /bin/rm /path/to/backupdir/$(date +%Y-%m-%d -d "-5 weeks")
Note that
We want to be careful not to run the backup script twice on the same day, for
example, when a quarterly backup happens on a Sunday. If the quarterly backup
cronjob is set to run (at 2:00AM), before the weekly backups (at 3:00AM), then
we can prevent the weekly backup from running by testing if the backup filename
already exists. This is the purpose of using
[ ! -f /path/to/backupdir/$(date +%Y-%m-%d-Q) ]
When we delete backups which are 5 weeks old, we do not want to delete quarterly backups.
We can prevent that from happening by naming the quarterly backups a little differently than the weekly backups, such as with a Q
:
% date +%Y-%m-%d-Q
2015-10-29-Q
so that the command to remove weekly backups,
/bin/rm /path/to/backupdir/$(date +%Y-%m-%d -d "-5 weeks")
will not remove quarterly backups.