Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

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.

share|improve this answer

This is the command I run to delete files:

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

The following is untested, but I'm sure you could modify it to delete directories by doing something like this recursive delete:

find /path/to/dir -mtime +1 -exec rm -rf {} \;
share|improve this answer
The second command is VERY BAD. Modification time of directories does not change when the contents of a file in the directory is modified, only when files are added or removed from the directory. Thus your second command will end up wiping out directories that shouldn't be. – Patrick Aug 22 '12 at 0:13
Ah, true. Good point. – David W Aug 22 '12 at 0:14
This is true however in this case I the directories are being created at the time of the files so this command will work for me. – liamTc Sep 11 '12 at 0:05
find $DNLD_DIR/* -mtime +7 -type d -print0 | xargs -0 rm -rf

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 the find conditions are wrong.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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