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.
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:
If you have directories which are frequently used, but sometimes empty, you could change the command to
This will only remove the directory if it doesn't match the modification time criteria, as well as it being empty.
This is the command I run to delete files:
The following is untested, but I'm sure you could modify it to delete directories by doing something like this recursive delete:
removes directory without checking for empty or not. I use it for removing directories that I created with directory name as yyyymmdd and i know i want everything in it be cleaned up including directory.
Be very careful using this, though. Any time you run
find | xargs rm -rf
you can ruin your day if thefind
conditions are wrong.