I am aware of find -mtime +x -delete, but how do I use it - or use it in a script - in order to delete all the "old stuff" (including hidden files) ? Eg, if I have a dir target_dir:

  • delete all folders and subfolders of target_dir whose content in any deep level has not changed by X days (i.e. delete old directory tree branches)
  • delete all the files in target_dir that didn't change by X days

Edit: related to this topic but the accepted answer there doesn't really work, because by first removing files we "update" the modification date of the old directories so that they are not removed in the second step... also not sure about possible hidden files/directories..

  • Does Stéphane's answer here help?
    – doneal24
    Feb 12 at 15:18
  • @doneal24: thank you.. I think I have found a simpler alternative...
    – Antonello
    Feb 12 at 20:30

1 Answer 1


After several tests, the simplest approach that I did find was to use simply:

find /path/to/dir -mtime +30 -delete

These delete everything excepts the branches that have newer stuff.

Note however that at the same time: (a) this would not work: find /path/to/dir/* -mtime +30 -delete; and (b) if /path/to/dir contains only old stuff and it has not been updated itself it will be deleted itself.

So my approach, as I wanted to keep the directory, is to run the first find command and then to check if the directory still exist, and if not, I recreate it.

  • If you have /path/to/dir/foo/, /path/to/dir/foo/bar/, and /path/to/dir/foo/bar/tmp, all with only old file, the last path will be deleted, the middle path's mtime updated, and the first path unchanged. You then have a branch that contained only old files that still exist after your commands are run.
    – doneal24
    Feb 13 at 16:11
  • Hmm... I'll double check and report... it worked with a very complex old directory, but I'll double check, thanks...
    – Antonello
    Feb 15 at 6:42
  • @doneal24 This is not my experience.. with find v4.8.0 (Ubuntu 22.04) path/to/dir is removed if it contains only old stuff, even if it has 3 or 4 directory levels...
    – Antonello
    Feb 15 at 15:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .