LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Delete backups older than 7 days through shell script (http://www.linuxquestions.org/questions/linux-newbie-8/delete-backups-older-than-7-days-through-shell-script-891821/)

Rk_Raj 07-15-2011 01:04 AM

Delete backups older than 7 days through shell script
 
Hi friends,

I am having my own testing server in which mySQL database will be backed up daily. in the format mysql_backup_dd/mm/yy.tar.gz in my home folder

I need to setup a cron job to delete the backups older than 7 days. please tell me how to do this.

EricTRA 07-15-2011 01:22 AM

Hello,

The easiest way is to write a Bash script that goes through the files in the backup directory, compares the date with the date saved in the file name and deletes if older then 7 days. Or just delete all backup files older then 7 days with a find command in combination with -exec. Have a look at the man page for find, more in particular the mtime option. Then you can run that script through a cron job.

Kind regards,

Eric

lithos 07-15-2011 09:06 AM

Using find command it would be like:
Code:

find . -name 'mysql_backup_*' -mtime +7 -delete
which would search for All mysql_backup_..... files within the current dir and subdirs and if found then delete it.

Works for me.

theNbomr 07-15-2011 10:51 AM

Sounds like a job for logrotate. Technically, it isn't a log file, but the type of data doesn't really matter.
--- rod.

eccenux 04-09-2013 02:47 AM

Sorry for digging out old thread, but it came up in Google...

For non-recursive search you need `-maxdepth 1` parameter, not `-xdev` (very different thing). You should also make sure you are deleting files and so you should add `-type f`.

So the command might look like this:
Code:

find /home/backup/mysql_*.gz -maxdepth 1 -type f -mtime +7 -delete
You could also use `-iregex` to control matches a bit more. I personally like POSIX RegExp (like in e.g. JavaScript). With regexp the command might look like this:
Code:

find /home/backup/mysql_*.gz -maxdepth 1 -regextype posix-extended -type f -mtime +7 -iregex '.+-[0-9]{4}0[^16][0-9]{2}-[0-9]{4}\.tar\.gz' -delete
Above will not match e.g. ...-20120131-... and so preserve January and June backups. Correct RegExp depends on your date/time format.


All times are GMT -5. The time now is 09:30 PM.