Delete Files Older Than x Days on Linux
The find utility on linux allows you to pass in a bunch of interesting arguments, including one to execute another command on each file. We'll use this in order to figure out what files are older than a certain number of days, and then use the rm command to delete them.
Command Syntax
find /path/to/files* -mtime +5 -exec rm {} \;
Note that there are spaces between rm, {}, and \;
Explanation
- The first argument is the path to the files. This can be a path, a directory, or a wildcard as in the example above. I would recommend using the full path, and make sure that you run the command without the exec rm to make sure you are getting the right results.
- The second argument, -mtime, is used to specify the number of days old that the file is. If you enter +5, it will find files older than 5 days.
- The third argument, -exec, allows you to pass in a command such as rm. The {} \; at the end is required to end the command.
This should work on Ubuntu, Suse, Redhat, or pretty much any version of linux.
The Geek is the founder of How-To Geek and a geek enthusiast. When he's not coming up with great how-to articles, he's probably writing at his personal blog. This article was written on 02/21/07 and tagged with: Ubuntu, Solaris, Suse Linux


How about just using the -delete flag rather than the -exec ?
"How about just using the -delete flag rather than the -exec ? "
Because if you have MANY files you will get maximum arguments exceeded..
so instead by doing exec you fork one process of rm per result… hope it helps
GOOD STUFF. Dead simple, and prevented me from having to try and write a complex script that would take me days. Implemented this in crontab in 5 minutes.
HUGE THANKS!
Now, can I pipe the results to a log file in the same line?
>>Now, can I pipe the results to a log file in the same line?
Yes:
bash -c 'date;find /path/to/files* -mtime +5 -exec rm -v {} \;;date' > ~/mylog
This way, you'll get a line at top with the date the line is executed (also a line at the bottom).
The last two semicolons are necessary, one is for find and one for bash.
there is an argument for find,so that also directory will be removed?
Pierissimo, well, the find command doesn't care if it's a file or a directory, so it'll delete both.
The above article mentions it "This can be a path, a directory, or a wildcard as in the example above." but in order to force delete the dirs, you need to do 'rm -fr' instead of just 'rm'. -f will force deletion and -r will do it recursively on all subdirs.
find can accept a -type argument where 'find -type f' will only find files, 'find -type d' will find dirs, and 'find -type l' will find links.