Ubuntu: Delete Files Older than a Certain Number of Days via the Terminal CodeUnit 10 AUG 2010

For example, let’s say you currently do non-incremental backups of your data on a daily business. If you don’t keep an eye on it, pretty soon your backup folder will run out of space and your system would come crashing down – so maybe it isn’t such a bad idea to run a cron in the background that deletes unnecessary files that are older than a specified number of days.

So how do we do this?

Well one solution is to make use of the powerful little find utility that comes with pretty much any variant of Linux. What this littly beauty does is offer you a whole lot of useful arguments, one of the most interesting being that of specifying a command to run on each file found!

Leveraging this functionality, we will first use the find command to locate our files older than a nuber of days and then use the rm command to delete them.

So how would the syntax for this look then?

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

(Note the spaces between rm, {} and ;)

The first argument is the path to the files, it being either a path, directory or even a wildcard as indicated above. Full path is probably the safest though!

The second -mtime argument is used to specify the number of days old a file needs to be in order to qualify for the search. If you enter +7 like we have, then find will return all files older than 7 days.

Finally, the -exec attribute allows us to pass our command (like rm) to the find function and apply it against each of the located files. The {} ; at the end is simply a control sequence to terminate the command.


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.