To delete files that are older than x days, we first find them using the find
command. Next, to delete the files, we use the execute action of the find
command and pass down the list of files to be deleted to the rm
command.
There are normally three types of time associated to a file: atime
, mtime
and ctime
. What we are talking about here is the mtime
or the last modification time.
To search for files that are 7 days old in your home directory, use the -mtime
test option of the find
command.
1 |
$ find /path/to/files -mtime 7 |
The above command has a slight problem. It will only match files that are exactly 7 days old. Well, that’s not technically correct. It will actually match all files that are more than 7 days old but less than 8 days old. In other words, it will match files that are more than 7 days old without considering the fractional part of the time. So files with a modification time of between 7 days 0 hours 0 mins 0 secs and 7 days 23 hours 59 mins 59 secs will match.
So to search for files that are more than 7 days old, append a ‘+’ to the argument passed to -mtime
.
1 |
$ find /path/to/files -mtime +7 |
Again, there is a problem. The above command will only match files with a modification time of more than 7 days – this means that the matched files will have to be 8 days or older. To match files that are 7 days or older, run find
as shown below.
1 |
$ find /path/to/files -mtime +6 |
Now, the find
command will list all the files that are 7 days or older.
Once we have confirmed the list of files from the find
command, we can proceed to delete the files.
1 |
$ find /path/to/files -mtime +6 -exec rm {} \; |
The -exec
option is used to call the rm
command. The “{} \;
” at the end is required. The “{}
” is used to pass the list of files to the rm
command and the “;
” is used to indicate the end of the arguments list to the -exec
option. The “\
” is used to to prevent expansion from the shell.
Race Conditions With -exec
The -exec
option of the find
command has race condition vulnerabilities due to a time gap between the point where find
decides that it needs to process the “-exec
” action and the point where the rm
command actually issues the unlink()
system call to delete the file from the filesystem. I will not go into details here, but if the find
command supports the -delete
or -execdir
options, use them instead. These options are available on the GNU version of find
.
1 |
$ find /path/to/files -mtime +6 -execdir rm {} \; |
1 |
$ find /path/to/files -mtime +6 -delete |