Ubuntu: Delete Files Older than a Certain Number of Days via the Terminal

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.

Nifty.

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Software & Websites, Tutorials and tagged , , , , , , , . Bookmark the permalink.
    blog comments powered by Disqus