Delete files older than X days in Linux

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, January 13, 2016

Follow me on Twitter as @mattiasgeniar

Sometimes you want to remove old files on a server, like old log files or temporary files created ages ago, that are no longer relevant. Here’s a quick command that lets you do that.

But first, let’s play safe and show you a command to view the files older than X days, so you can review the list first before you launch the delete-command.

$ find . -mtime +180 -print

To break it down: we use find in the current directory (the dot .) and list all files with a modification date that’s older than 180 days. After that, we print the files to stdout with the -print command (which, technically, is obsolete – you can omit that parameter and it’ll still work, but it makes for a clearer example).

To pass an other directory, simply replace the dot:

$ find /to/your/directory -mtime +180 -print

Now, to actually delete the files older than X days, you can use any of these variants. Be careful though, there’s no trashbin or confirmation in this case, once you copy/paste this, it’ll delete everything in your current working directory older than 180 days. ;-)

$ find . -mtime +180 -delete;
$ find . -mtime +180 -exec rm -f {} \;

As before, the -mtime parameter is used to find files older than X. In this case, it’s older than 180 days. You can either use the -delete parameter to immediately let find delete the files, or you can let any arbitrary command be executed (-exec) on the found files.

The latter is slightly more complex, but offers more flexibility if want to copy them to a temp directory instead of deleting. In that case, you can swap out the rm with an mv.



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.