Delete Files Older Than x Days on Linux

By Lowell Heddings on February 21st, 2007

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.

Want to Learn More? Get Linux Training from the Linux Foundation

Learn everything you could want to know about Linux with comprehensive online Linux courses and certification tests that include the real-world experience and first-hand knowledge of what it takes to be a successful Linux developer or system administration professional, all from a web browser in the comfort of your home.

The Linux Foundation is the nonprofit consortium dedicated to fostering the growth of Linux. Founded in 2000, they are supported by the leading technology companies and developers from around the world.

See All Linux Foundation Courses

Lowell Heddings, better known online as the How-To Geek, spends all his free time bringing you fresh geekery on a daily basis. You can follow him on if you'd like.

  • Published 02/21/07
More Articles You Might Like

Enter Your Email Here to Get Access for Free:

Go check your email!