Use the FIND command to reduce old backup/files


A Bash script to remove/cleanup backups (or any files matching the date field in filename).

Uses FIND command – Example shown retains/saves 1st of month backup only if older than 90 days.

Create a shell script:

[prism:bash]$ sudo nano /opt/scripts/cron_prune_backups.sh[/prism:bash]

Edit for days desired (change +90 to your choice, and/or day of month ’01’, and/or filename) and save:

[prism:bash]#!/bin/bash

DS=`date “+%Y-%m-%d %H:%M:%S”`
FINDPATH=/opt/mysql-backups
LOG=”$FINDPATH”/mysql-backup-removal.log

### find >= 90 day – but leave/exclude a 1st day of month forever…
find “$FINDPATH”/backupname_* -name ‘backupname_??-01-*’ -prune -o -mtime +90 -exec ls {} \; >> “$LOG”[/prism:bash]

Set some permissions:

[prism:bash]$ sudo chown root:root /opt/scripts/cron_prune_backups.sh
$ sudo chmod 744 /opt/scripts/cron_prune_backups.sh[/prism:bash]

Test run:

[prism:bash]$ cd /opt/scripts/ && sudo ./cron_prune_backups.sh[/prism:bash]

Running the above should produce a `ls` file list in your defined log.

The test above only lists files.
If the correct files are listed for deletion, just replace the find line with this (added ‘rm’):

[prism:bash]find “$FINDPATH”/backupname_* -name ‘backupname_??-01-*’ -prune -o -mtime +90 -exec ls {} \; -exec rm {} \; >> “$LOG”[/prism:bash]

Add to root crontab and you are done:

[prism:bash]$ sudo crontab -e[/prism:bash]

Adjust to your liking and save:

[prism:bash]## run on 2nd of month/each month:
0 0 2 * * /opt/scripts/cron_prune_backups.sh[/prism:bash]

Leave a Reply

Your email address will not be published. Required fields are marked *