Killing “find” Errors

I’ve used the unix filesystem search utility find for many years. Though, like most things, until forced to learn its deeper secrets, I generally get by with only the most basic knowledge.

One of the cool things about find is that you can specify a search and then execute an action on the results, all in one command.

This example is probably my most common use of find:

find . -type d -name .svn -exec rm -fr {} \;

This means: find, in the current directory (.), a directory (-type d), named .svn (-name .svn), and for every result (-exec) remove that directory (rm -fr {}) .  The “{}” represents the matched path string, and the “\;” is required to end the “-exec” command.

Here’s a sample of what this looks like, including output:

$ find . -type d -name .svn -exec rm -fr {} \;
find: ./.svn: No such file or directory
find: ./getid3-2.0.0b4/.svn: No such file or directory
find: ./getid3-2.0.0b4/extras/.svn: No such file or directory
find: ./getid3-2.0.0b4/getid3/.svn: No such file or directory

This is great, and I’ve used this exact syntax for years. But today I ran into a problem. I wanted to run this exact command as part of a custom build script in Xcode. When this command ran I had 81 errors popup in my build results! What happened is that all thos “No such file or directory” messages are actually errors, and Xcode reported them as such.

The solution is to add one extra argument: -depth . This causes find to do a depth-first traversal of the sub-directories being searched. That is, find will check the contents of directories before acting (eg, running an -exec command) on the directory in question. The default is to act on the directory (in our case, removing it) before attempting to visit it’s contents. So after we removed the directory, find was still trying to look at it; -depth fixes that.

So, the final answer is, I now use:

find . -type d -name .svn -depth -exec rm -fr {} \;

Yes, this is a slightly verbose explanation for something so simple, but maybe it will help someone else.

Leave a Reply

Your email address will not be published. Required fields are marked *