cron job to remove files with specific name
Solution 1
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.
Solution 2
Instead of parsing the file name, you can also check the modification time of a file.
The next command looks in the /tmp/mysqldumps
directory. Filenames starting with mydb.
and ending on .gz
, older than 30 days are removed.
find /tmp/mysqldumps -name 'mydb.*.gz' -mtime +30 -exec rm {} \;
Solution 3
You can remove files older than e.g. 30 days using a command like
rm -f `find /tmp/mysqldumps -mtime +30 -name mydb.\*.gz`
Related videos on Youtube
Alaa Alomari
Updated on September 18, 2022Comments
-
Alaa Alomari almost 2 years
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)?
-
lsd about 13 yearsIf you have gnu date (and possible others), you can do
date -d 'last month' +'%Y-%m-%d'
, which will do the same thing as your printf (at the top) with less processes and more robust. Subtract 1 from month 1, January, and you get 0, which will result in 2011-00-04, which is not valid. Letting date to it for you will give you the correct results.