Unix & Linux: Delete files older than X days + (3 Solutions!!)
Channel: Roel Van de Paar
Date: 2020-08-06

Unix & Linux: Delete files older than X days +


The Question: 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?

Solutions: Please watch the whole video to see all solutions, in order of how many people found them helpful

== This solution helped 10 people ==
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.

== This solution helped 274 people ==
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).

With thanks & praise to God, and with thanks to the many people who have made this project possible! | Content (except music & images) licensed under cc by-sa 3.0 | Music: https://www.bensound.com/royalty-free-music | Images: https://stocksnap.io/license & others | With thanks to user Teddy291 (https://unix.stackexchange.com/users/102085), user Stephen Kitt (https://unix.stackexchange.com/users/86440), user Julius (https://unix.stackexchange.com/users/139701), user Gilles 'SO- stop being evil' (https://unix.stackexchange.com/users/885), user basic6 (https://unix.stackexchange.com/users/58393), user apaul (https://unix.stackexchange.com/users/107719), and the Stack Exchange Network (http://unix.stackexchange.com/questions/194863). Trademarks are property of their respective owners. Disclaimer: All information is provided "AS IS" without warranty of any kind. You are responsible for your own actions. Please contact me if anything is amiss at Roel D.OT VandePaar A.T gmail.com.