Delete Files Older Than X Days

I was tasked with auto removing files from a linux FTP site that were older than 14 days. Unfortunately the files were all located in the ~ (home) directories.

I originally tried:
find /home/* -mtime +14 -type f
This command attempts to find ALL (*) files in the home (/home/) directory with a modified time of 14 days (-mtime +14) and only files not directories (-type f)

The command found all the files ok, but it was also listing the hidden files:

/home/user/.profile
/home/user/.bash_logout
/home/user/.bash_history
/home/user/.bashrc

So I decided to use regex:
find /home/* \( ! -regex '.*/\..*' \) -type f -mtime +14
This worked!

Now to add the removal of the files:
find /home/* \( ! -regex '.*/\..*' \) -type f -mtime +14 -exec rm {} \;

I saved this as delete_files, then made it runnable, and cron’d it up:
chmod +x delete_files
crontab -e
@daily ./delete_files #Delete Files Older Than 14 Days in Home Dirs

This worked on my Ubuntu 10.04.3 LTS system, but the commands should work on all the flavors.

Leave a Reply

Your email address will not be published. Required fields are marked *