I need to delete all files older than 5 days in all subfolders, but not the folders themselves. I know the command:

find /path/to/files* -mtime +5 -exec rm {} \;

But how can I tell Ubuntu to check in all subfolders, yet never delete the folders themselves. Will I need a -maxdepth 5 somewhere?


  • 1
    -type f will find only files, not folders. – Jos Oct 4 '16 at 8:43
  • Will it automatically check subfolders? – warhansen Oct 4 '16 at 8:51
  • 1
    Yes, that is the default behaviour of find. – Jos Oct 4 '16 at 8:51
  • Awesome, thanks, will test! Can you make your comment a answer so I can upvote once tested? – warhansen Oct 4 '16 at 8:52
  • Someone jumped in before me. – Jos Oct 4 '16 at 8:53

First of all, don't give a glob to find (no files*), just give it the parent directory (/path/to/). It will deal with recursing into it and finding all files. Next, rm will never delete directories, so you don't need to worry about that either. Still, the simplest way is:

find /path/to/ -type f -mtime +5 -delete

Note the -type f which tells find to only look at files and the -delete which, well, deletes them. This is more efficient than calling a separate rm for each result.

| improve this answer | |
  • find /path/to/ -type f -mtime +5 will match files starting from 6 days old, i am not sure if that's what OP wants. For 5 days or more, find /path/to/ -type f -mtime +4 – heemayl Oct 4 '16 at 9:07
  • @heemayl good point, but since the OP said "older than 5 days", I assume that's what they wanted. – terdon Oct 4 '16 at 9:08

You can also use

find /path/to -type f -mtime 5+ -exec rm {} \;
| improve this answer | |
  • Edited answer for subfolder use – Tolga Ozses Oct 4 '16 at 10:01
  • 4
    What's the advantage of -exec rm {} \; over -delete? As far as I can tell it'll do the same thing but slower because it spawns a new rm process for each match. You could use -exec rm {} + to invoke rm on multiple files at once but that's still one more fork+exec than necessary. – David Foerster Oct 4 '16 at 10:03
  • The keyword is "also". Didn't know about the performance. – Tolga Ozses Oct 4 '16 at 10:05
  • 1
    Sure. That's why I didn't vote to delete your answer but ask about its benefits. I still think it's suboptimal. – David Foerster Oct 4 '16 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.