Delete files older than X days +
I have found the command to delete files older than 5 days in a folder
find /path/to/files* -mtime +5 -exec rm {} ;
But how do I also do this for subdirectories in that folder?
It’s the same. You just have to provide the parent directory rather than the prefix of files. In your example, it would be:
find /path/to -type f -mtime +5 -exec rm {} ;
This will delete all the files older than 5 days which are under /path/to
and its sub-directories.
To delete empty sub-directories, refer to @Costas comment above.
Be careful with special file names (spaces, quotes) when piping to rm.
There is a safe alternative – the -delete option:
find /path/to/directory/ -mindepth 1 -mtime +5 -delete
That’s it, no separate rm call and you don’t need to worry about file names.
Replace -delete
with -depth -print
to test this command before you run it (-delete
implies -depth
).
Explanation:
-mindepth 1
: without this,.
(the directory itself) might also
match and therefore get deleted.-mtime +5
: process files whose
data was last modified 5*24 hours ago.
Note that this command will not work when it finds too many files. It will yield an error like:
bash: /usr/bin/find: Argument list too long
Meaning the exec system call’s limit on the length of a command line was exceeded. Instead of executing rm that way it’s a lot more efficient to use xargs. Here’s an example that works:
find /root/Maildir/ -mindepth 1 -type f -mtime +14 | xargs rm
This will remove all files (type f) modified longer than 14 days ago under /root/Maildir/ recursively from there and deeper (mindepth 1). See the find manual for more options.
find . -mtime +3 -type f -not -name '*pid*' |xargs rm -rf
Disclaimer: I’m the current author of rawhide (rh) (see https://github.com/raforg/rawhide).
It probably makes the most sense to delete empty directories after deleting files that are older than X days. The modification time of directories is when entries were added or deleted from them. Deleting old files will update the modification time of the directory that contained them to the time of the deletion. So, you don’t want to refer to the modification time of the directories themselves. Just delete empty directories. Deleting files at least 5 days old, and then deleting the resulting empty directories can be done with:
rh -UUU /path/to 'f && old(5*days)
rh -UUU /path/to 'd && empty'
-UUU
unlinks/removes/deletes the matching files.
The rest is the search criteria.
f
matches regular files.
old(5*days)
matches files modified at least 5 days ago.
d
matches directories.
empty
matches empty directories (and regular files of zero size).
It can also be done with find, of course:
find . -type d -empty -delete
As stated by Costas.