If you want to know that find
finds some files abc
and that at least one of them contains the string xyz
, then you can probably use:
if find . -name 'abc' -type f -exec grep -q xyz {} +
then : All invocations of grep found at least one xyz and nothing else failed
else : One or more invocations of grep failed to find xyz or something else failed
fi
This relies on find
returning an exit status for its own operations, and a non-zero exit status of any of the command(s) it executes. The +
at the end groups as many file names as find
thinks reasonable into a single command line. You need quite a lot of file name (a large number of fairly long names) to make find
run grep
multiple times. On a Mac running Mac OS X 10.10.4, I got to about 3,000 files, each with about 32 characters in the name, for an argument list of just over 100 KiB, without grep
being run multiple times. OTOH, when I had just under 8000 files, I got two runs of grep
, with around 130 KiB of argument list for each.
Someone briefly left a comment asking whether the exit status of find
is guaranteed. The answer is 'yes' — though I had to modify my description of the exit status a bit. Under the description of -exec
, POSIX specifies:
If any invocation [of the 'utility', such as grep
in this question] returns a non-zero value as exit status, the find
utility shall return a non-zero exit status.
And under the general 'Exit status' it says:
The following exit values shall be returned:
0
— All path operands were traversed successfully.
>0
— An error occurred.
Thus, find
will report success as long as none of its own operations fails and as long as none of the grep
commands it invokes fails. Zero files found but no failures will be reported as success. (Failures might be lack of permission to search a directory, for example.)