Linux – cron job to remove files with specific name

crondatelinuxUbuntu

I have this in my crontab

0 3 * * * mysqldump --host=10.100.100.3 --user=username --password=mypass --routines DBName | gzip > /tmp/mysqldumps/mydb.`date +"\%Y-\%m-\%d"`.gz

now I need to create another cron job to do this scenario
assuming we are in 3rd of May 2011
I want to remove the file that has been created one month ago ie. rm mydb.2011-04-03.gz

Any idea of how to generate this cron job (how to generate the name of the file to be deleted)?

Best Answer

You have serveral options; I propose two of them:

Remove the file by date (each day the destination dir will be searched for files older than one month and the matches will be deleted):

10 3 * * * find /tmp/mysqldumps/ -maxdepth 1 -ctime +30 -exec rm {} \;

Remove the file by name:

10 3 * * * rm /tmp/mysqldumps/mydb.`date -d "last month" +'%Y-%m-%d.gz'`

I prefer the former one because is more robust. Also if the remove cron job for some reason one day doesn't run, the next day the former command will do the trick. In my second example the file wont be deleted.