Using Find Command To Remove Old Backups
I have been using this command to remove old backups on my server:
find /backups/etcbak/ -mtime +7 -exec rm {} ; && find /backups/varlogsbak/ -mtime +2 -exec rm {} ; && find /backups/varmysqlbak/ -mtime +7 -exec rm {} ;
The above commands works great at removing actual files in the targeted directories.
My problem is:
How do I get the above command to also remove subdirectories?
(I added a mysql backupscript that creates subdirectories in the targeted directories based upon the current date).
I tried to adjust the above command as follows:
find /backups/etcbak/ -mtime +7 -exec rm -rf {} ; && find /backups/varlogsbak/ -mtime +2 -exec rm -rf {} ; && find /backups/varmysqlbak/ -mtime +7 -exec rm -rf {} ; && find /backups/varmongobak/ -mtime +7 -exec rm -rf {} ;
But it simply will not remove old subdirectories.
The goal is to delete files -and- directories that may exist in the targeted directories.
For example:
/backups/etcbak/filename (where "filename" is deleted after 7 days)
and
/backups/etcbak/dirname
(where the subdir named "dirname" and its contents are also deleted after 7 days)
Anyone know how to crack this? thx
My approach would be to delete files according to your criterion and then remove empty directories
find /backups/etcbak /backups/varmysqlbak /backups/varmongobak -depth -type f -mtime +7 -delete
find /backups/varlogsbak -depth -type f -mtime +2 -delete
find /backups/etcbak /backups/varlogsbak /backups/varmysqlbak /backups/varmongobak -mindepth 1 -depth type d -delete 2>/dev/null
Strictly speaking, -depth
isn’t required as it’s implied by -delete
, but I think it’s useful to see it and be reminded that it’s active