Efficient Finds
Recently, I've seen a lot of suggestions along the lines of:
find . -name foo -exec ls -l {} \;This is incredibly inefficient, because for each and every matching file, ls will be executed. Fortunately, we can do better by using xargs. xargs takes a list of lines from stdin and uses them to build up a command line. It takes special care to not exceed the maximum command line length by splitting the input up into multiple commands if it is needed. So, with that knowledge, we can replace our original command with:
find . -name foo | xargs ls -l
There is one slight problem with this command; it isn't space-safe. xargs splits arguments on whitespace, so "file name" will be incorrectly passed to the command as "file" "name". Fortunately, xargs has an option to delimit parameters by the null character, and as our luck would have it, find has a suitable option to produce output in this format. This means our command is now:
find . -name foo -print0 | xargs -0 ls -l
mlocate can do something similar:
locate foo -0 | xargs -0 ls -l
GNU find has one more trick up its sleeve. It has a modified version of -exec that will do the same thing as xargs, so we could have written our original command as:
find . -name foo -exec ls -l {} +Every process is sacred; every process is great. If a process is wasted, God gets quite irate. Please make sure you try to use one of the latter forms and not the first form, and make a happy deity. :)