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?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityBe 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.find
argument is a filter that uses the result of the previous filter as input. So make sure you add the -delete as the last argument. IE: find . -delete -mtime +5
will delete EVERYTHING in the current path.
-mmin
in place of -mtime
, you can specify time in terms of minutes.
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 /root/Maildir/ -mindepth 1 -type f -mtime +14 -print0 | xargs -r0 rm --
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.
+
in that case. -- 2) better to write -exec rm '{}' +
to fend off the evil of files with special characters (spaces, newlines, etc...) in their name.
-exec rm {} +
, if there are too many files, rm
may complain: Argument list too long
. So yes, -delete
does seem like the much more sensible option.
Oct 29, 2021 at 13:48
find . -mtime +3 -type f -not -name '*pid*' |xargs rm -rf
find /path/to -type d -empty -delete
rm test one
. (Which will delete a file called "test" and a file called "one", but not a file called "test one"). Hint: -delete or -print0find
to avoid issues with special characters, as mentioned in the answer's first line. E.g.:find /path/to/files/ -exec somecommand '{}' \;