How to detect whether “find” found any matches

findosx

Is there an idiomatic means to detect whether "find" found any matches? I'm currently using

COUNT=`find ... | wc -l`
if [ "$COUNT" -gt 0 ]; then

but this seems a little indirect to me. Also, I'd like find to stop searching once it's found a match, so it doesn't waste time and effort. I just need to know whether or not there are any files that match.

Update: I made the mistake of writing my question without the code in front of me: I use wc -l in a different case, where I need to know the total number of found files anyway. In the case where I'm only testing for whether there are any matches, I was using if [ -z $(find …) ].

Best Answer

If you know you have GNU find, use -quit to make it stop after the first match.

Portably, pipe the output of find into head -n 1. That way find will die of a broken pipe after a few matches (when it's filled head's input buffer).

Either way, you don't need wc to test whether a string is empty, the shell can do it on its own.

if [ -n "$(find … | head -n 1)" ]; then …
Related Question