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
    Commented Jul 17, 2013 at 23:46

1 Answer 1

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. Commented Jul 18, 2013 at 14:44
  • @KoreyHinton - I understand the difference, but thought that find would split it up based on ARG_MAX like xargs would.
    – jordanm
    Commented Jul 18, 2013 at 14:53

You must log in to answer this question.

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