Mike Mead

Delete files older than a specified period

Written by Mike

May 25, 2014


Delete files older than a specified period

A common administration task is to remove old, unnecessary files to prevent disk space from running out. Using find with the -exec switch you can easily achieve this and even automate the task with a cron job.

Let's start with building the criteria:

find /path/*.tmp

The above will find all files ending in .tmp at the specified path.

Add a time condition:

find /path/*.tmp -mtime +14

-mtime +14 will find files older than 14 days; -mtime +7 will find files older than 1 week.

Specify that we're looking for files only:

find /path/*.tmp -mtime +14 -type f

You can add other find switches to build your search criteria:

find /path/*.tmp -mtime +14 -type f -size -2000k

Size less than ~2MB.

find /path/*.tmp -mtime +14 -type f -size +2000k

Size more than ~2MB.

Time to do something with the files found:

find /path/*.tmp -mtime +14 -type f -exec rm {} \;

-exec Start 'exec'; rm delete; {} each file found; \; End 'exec'.

You can use rm -r to remove recursively or rm -rf to forcefully recursively.

How about a cron job to automate this task?:

00 01 * * 0 find /path/*.tmp -mtime +7 -exec rm {} \; > /dev/null 2>&1

The above example will run at 1AM every Sunday and remove every file in /path/, ending in .tmp and older than 7 days.

> /dev/null 2>&1 redirects both errors and standard to /dev/null (i.e. discards it).

comments powered by Disqus