How to delete directories contents (and not the directory itself) using find -exec and rm?

I'm trying to delete the content of some directories (but not the directory itself) using this:

find -type d -name someDirs -exec rm -rf {}/* \;

But it doesn't work. Any tips?


Solution 1:

The problem with your command is that wildcard expansion is done by your shell before the command is actually called. As your shell does not find a file that matches {}/* (as you don't have a directory with a literal name {} in the current directory), the * is passed to the command unchanged, which will then be modified by find to delete files named literal * in your someDirs directories, as the rm command will not expand wildcards (again). You can "debug" this by running

find -type d -name someDirs -exec echo rm -rf {}/* \;

instead. To make sure that the shell has a chance to expand your *, let exec spawn another shell which can expand the * (and protect the command from being expanded first with single quotes) like this:

find -type d -name someDirs -exec sh -c 'rm -rf {}/*' \;

or test it like this:

find -type d -name someDirs -exec sh -c 'echo rm -rf {}/*' \;

Solution 2:

You can give the directory (or directories) as arguments to find and tell it to skip it with the -mindepth option:

-mindepth levels
Do not apply any tests or actions at levels less than levels (a non-negative integer).
-mindepth 1 means process all files except the command line arguments.

So, your command would be:

find SomeDir1 SomeDir2 -mindepth 1 -exec rm -rf '{}' \+