Linux – Find and delete directories older than time

linux

I have a command which I am using to find and delete files within a directory older than a specified time. The command is:

sudo find /path/to/dir/* -daystart -mtime +7 -delete

How can I modify this command to delete directories as well as files within the specified directory.

Best Answer

You probably don't want to remove directories based on their modification time. What you probably want to do is remove a directory once it has no files left in it.
One way to solve this would be the following:

find /path/to/dir -type d -empty -exec rmdir {} \;

If you have directories which are frequently used, but sometimes empty, you could change the command to

find /path/to/dir -type d -empty -daystart -mtime +7 -exec rmdir {} \;

This will only remove the directory if it doesn't match the modification time criteria, as well as it being empty.