Super User is a question and answer site for computer enthusiasts and power users. 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'm running the following command:

find /var/www/html/content/processing -type d -mtime +1 -exec rm -rf {} \;

I would like to delete all the folders under the processing folder (the processing folder should never be deleted).

The command is deleting the processing folder as well. How do I limit the script to delete only the folders under that folder?

share|improve this question
up vote 14 down vote accepted

The easiest way would be to just add -mindepth 1, which will skip the first depth hierarchy and thus leave out your parent directory.

Also, you don't need an extra -exec call to rm, you can just delete the folders directly if they're empty.

find /var/www/html/content/processing -mindepth 1 -type d -mtime +1 -delete

If they're not empty:

find /var/www/html/content/processing -mindepth 1 -type d -mtime +1 -exec rm -rf {} \;

If you're lazy you can also have a wildcard expanded. Since * doesn't include the current directory by default (unless dotglob is set), you could also do:

find /var/www/html/content/processing/* -type d -mtime +1 -delete

However, this would also not include hidden folders, again due to the dotglob option.

share|improve this answer
Hi, I get "find: warning: you have specified the -mindepth option after a non-option argument -type, but options are not positional (-mindepth affects tests specified before it as well as those specified after it). Please specify options before other arguments. " and also "find: cannot delete `/folder/50d82faf0e09e': Directory not empty" – Elad Dotan May 5 '13 at 7:14
Add mindepth before type then. To delete the directories when not empty you can stick with the rm approach you had originally. – slhck May 5 '13 at 12:25

The problem is that find returns the current directory (.) along with the other directories, so it deletes the processing folder as well as the subdirectories. A quick way to get around that would be to append the option

-not -name .

which stops find from outputting the current directory, and in turn stops it from being deleted.

That would work if you were running the command within the processing directory, so to allow for the fact that you are using an absolute path:

-not -name /var/www/html/content/processing

And the whole command would be:

find /var/www/html/content/processing -type d -mtime +1 -not -name /var/www/html/content/processing -exec rm -rf {} \;
share|improve this answer

You must log in to answer this question.

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