Linux: Delete files older than 30 days.

This is a short guide on how to use the Linux find utility to remove old files.

The other day, I had to create a cron job that purged cached files that were older than 30 days. The files in question were stored on my Ubuntu 14.04.5 LTS server, inside a directory called cached_files.

find command.

To do this, I used the find utility, which can be run via the terminal. Here is a sample of what I used:

sudo find /home/shared/cached_files -type f -mtime +30 -delete

A quick explanation of the command above:

  • We told the find utility to look in the directory /home/shared/cached_files
  • We used -type f because we are looking for regular files.
  • We used -mtime +30 because we are looking for files that were last modified over 30 days ago. The caching system on my server uses the last modified time because it allows me to keep files that are still being accessed. If you want to delete files that are older than 7 days, then you can change this option to -mtime +7
  • At the end of the command, the -delete action is used to delete the file.

Note that the command above will also go through sub-directories looking for old files to delete.

Hopefully, you find this command to be useful.