Tuesday, October 26, 2021

[SOLVED] Delete all directories and its files older than a 60 days regardless of whether the directory is empty or not

Issue

I'm trying to delete all directories in /mnt/games/codes that are older than 60 days. The directories could be empty or not, but I want them all deleted.

So looking on here, I found this command:

find /mnt/games/codes/* -mtime +60 -type d -exec rm -rf {} \;

But it gives me this error:

No such file or directory

So then I tried this:

find /mnt/games/codes/* -mtime +60 -type d -exec rmdir {} \;

But it's giving me a brand new error that looks like this:

Directory not empty

Is there a way to delete these with one command?

Thanks!


Solution

Your issue is because find is deleting its search base directories before it has finished iterating these, so calling your rm -rf on already deleted entries.

This is easily fixed by adding the -depth option.

Also, you should really end the rm options with a double dash --, to prevent having arguments provided by the find command, to be interpreted as options arguments by the rm command.

find /mnt/games/codes/ -depth -mtime '+60' -type d -exec rm -rf -- {} \;


Answered By - Léa Gris