I want to remove certain directories from a hiearchy using 'find -exec'

find $rootdir -type d -name target -exec rm -rf {} \;

I get error messages

find: `foo/bar/target': No such file or directory

because 'find -exec' apparently works in pre-order, i.e. it does the work first and then visits the children. I don't want to simply redirect the error messages to /dev/null, because they might be meaningful. Any suggestions?


You are looking for the -d or -depth option

 -depth  Always true; same as the -d option.

 -d      Cause find to perform a depth-first traversal, i.e., directories
         are visited in post-order and all entries in a directory will be
         acted on before the directory itself.  By default, find visits
         directories in pre-order, i.e., before their contents.  Note, the
         default is not a breadth-first traversal.

Be careful with -depth, if you add a number it changes meaning.

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.