In a Linux file system, files are stored within a single directory structure, called a virtual directory. The virtual directory contains files from all the computer’s storage devices and merges them into a single directory structure. This structure has a single base directory called the root directory (/) that is often simply called root. Locating files and directories is a common operation for any Linux SysAdmin.

You can view, create, copy, move and delete files in the virtual directory structure from the command line or using graphical interface utilities. In this article we describe how you can locate files and directories older than an x number of days or minutes. The results from the search can be subjected to delete operation if that’s the desired action.

Using the find Command

With the find command you can locate files based on data, such as ownership, time modification, file permissions, and so on. The basic command syntax is as follows:

$ find [ PATH ...] [ OPTION ] [ EXPRESSION ]

When using find you designate a starting point directory using the PATH argument. find will then search through that directory and all its subdirectories (recursively) for the file or files you seek. To see all supported command options use:

$ man find
$ find -help

The find command’s commonly used options and expressions are:

Find optionExpressionDescription
-namepatternLocate files whose name matches pattern
-sizenLocate files whose size matches n
-usernameLocate files whose owner is name.
-groupnameLocate files whose group is name
-gidnLocate files whose group ID is equal to n.
-cminnLocate files whose status changed n minutes ago.
-mminnLocate files whose data changed n minutes ago.
-permmodeLocate files whose permissions matches mode (octal or symbolic)
-nouserN/ALocate files where no username exists for the file’s user ID
-maxdepthnWhen searching for files, traverse down only n levels.
-inumnLocate files whose inode number is equal to n.
-emptyN/ALocate files that are empty and are a regular text file or a directory
-mtimenLocate files whose data was last modified n*24 hours ago

Files files older than x minutes in Linux

We’ll use -mmin to locate files whose data changed n minutes ago.

Example below finds files older than 5 minutes in the current working directory:

$ find ./ -type f -mmin +5

We can delete the files using the find and -delete option:

find ./  -mmin +5 -delete

Confirm files are deleted using

$ ls

The following command will yield same results:

$ find  ./ -mmin +5 -type f -exec rm -fv {} \;
removed './file1.txt'
removed './file2.txt'
removed './file3.txt'

For directories replace -type f with -type d

Find files older than x days in Linux

Find files older than 7 days:

$ find  ./ -mtime +7 -type f

$ find  /some-dir -mtime +7 -type f

Only directories:

$ find  ./ -mtime +7 -type d

Delete files older than 7 days:

find  ./ -mtime +7 -type f -delete

You can use more filters e.g file permissions, user/group ownership.