Purge old files on Linux/Unix using “find” command

on Tuesday, 8 January 2013

Purge old files on Linux/Unix using “find” command



I've noticed that one of our interface directories has a lot of old files, some of them were more than a year old. I checked it with our implementers and it turns out that we can delete all files that are older than 60 days.
I decided to write a (tiny) shell script to purge all files older than 60 days and schedule it with crontab, this way I won't deal with it manually. I wrote a find command to identify and delete those files. I started with the following command:
find /interfaces/inbound -mtime +60 -type f -maxdepth 1 -exec rm {} \;
It finds and deletes all files in directory /interface/inbound that are older than 60 days.
"-maxdepth 1" -> find files in current directory only. Don't look for files in sub directories.
After packing it in a shell script I got a request to delete "csv" files only. No problem... I added the "-name" to the find command:
find /interfaces/inbound -name "*.csv" -mtime +60 -type f -maxdepth 1 -exec rm {} \;
All csv files in /interface/inbound that are older than 60 days will be deleted.
But then, the request had changed, and I was asked to delete "*.xls" files further to "*.csv" files. At this point things went complicated for me since I'm not a shell script expert...
I tried several things, like add another "-name" to the find command:
find /interfaces/inbound -name "*.csv" -name "*.xls" -mtime +60 -type f -maxdepth 1 -exec rm {} \;
But no file was deleted. Couple of moments later I understood that I'm trying to find csv files which is also xls files... (logically incorrect of course).
After struggling a liitle with the find command, I managed to make it works:
find /interfaces/inbound \( -name "*.csv" -o -name "*.xls" \) -mtime +60 -type f -maxdepth 1 -exec rm {} \;


You are welcome to leave a comment.

0 comments:

Post a Comment