2

I need to find a way to remove sub-directories from within a particular directory without receiving an error if no sub-directories exist. This command will successfully remove sub-directories if they exist

find /path/to/dir/* -maxdepth 1 -type d -exec rm -rf {} \;

But if none exist I will get this error:

find: /path/to/dir/*: No such file or directory

Also, I am using the find instead of just plain rm because there are too many directories for rm to handle and they must be handled individually with find.

Also I noticed that find /path/to/dir/ -maxdepth 1 -type d -exec rm -rf {} \; with no wildcard actually removes the dir directory as well.

1
  • If the problem with using rm is ARG_MAX from the glob, find is going to have the same problem since that is a global limitation. – jordanm Jul 17 '13 at 23:46
3

You can use the -mindepth parameter from find, to prevent it from matching . in the target directory. This should resolve your issues.

find /path/to/dir/ -mindepth 1 -maxdepth 1 -type d -exec rm -rf {} +
2
  • Adding mindepth did solve my problem. Thanks! By the way, with + at the end I get "Argument list too long" error. This will work if + is changed to \; See Using ; vs + with exec in find. – Korey Hinton Jul 18 '13 at 14:44
  • @KoreyHinton - I understand the difference, but thought that find would split it up based on ARG_MAX like xargs would. – jordanm Jul 18 '13 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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