Delete files older than

It is just one of those things that as an admin, you sometimes come across. There’s a directory somewhere that fills up with clutter. Every day, programs dump temporary files there or users upload stuff and before long, there are thousands of files of debris and cruft. How do you keep this directory neat and tidy? Easy, you just make a small script that will delete files older than x days.

On Linux, you can easily search for files to delete using the find command. Let’s say you want to keep all files for a week and then get rid of them. Here’s how you find all files that are older than 7 days.

$ find /path/to/files -mtime +7 -type f

This command finds all ordinary files in the specified directory that were modified more than 7 days ago. Why modified and not created? Easy: this ensures you delete files that really haven’t been touched in the last 7 days.
If you run the above command, you’ll probably get a listing of files. If this list seems correct, you can remove those files by expanding the command above just a little.

$ find /path/to/files -mtime + 7 -type f -exec rm {} \;

The above command list all the ordinary files in the specified directory that were modified more than 7 days ago and then runs the command rm (remove) against them. Depending on how many matching files there are in this directory, this command can take a while.

Sticking the above command in a simple shell script, you can schedule it via cron and presto, that cluttered directory will be automatically cut to size without you having to worry about it.