Delete Files Older Than x Days

by admin on November 23, 2010

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  x -exec rm {} ;

Note that there are spaces between rm, {}, and ;

Example:

find /path/to/files* -mtime +7 -exec rm {} ;

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 +7, it will find files older than 7 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, CentOS or pretty much any version of linux.

More:

If you happen to get an error:

/usr/bin/find argument list too long

You try again with the following command:

find /path/to/files* -type f -mtime +7 -print 0 | xargs -0 -rm

Leave a Comment

Previous post:

Next post: