Immediately after a command exits, its exit code is stored in the special variable "
$?".
echo that to see what you'll get, or test it in the usual ways.
But actually you generally don't need to use any kind of test here. The
[..] test brackets are just a command like any other, and give an exit code, which is what the
if/
while/
until constructs are actually working with. So you can replace it with just about any command if you want.
Code:
if grep -q 'foobar' file.txt ; then
echo 'string found in file'
else
echo 'string not found in file'
fi
find, however, doesn't appear to give you the kind of exit code you want. It only gives a non-zero status if there are errors in the command. So for that you have to do something like capture the output in a variable/array and test that for the existence of a string.
Or actually, the way you have it written in the OP may do just as well, since the
$(...) will be substituted with the text output of the command.
[..] will exit successfully if it finds a text string (although it's better to use the explicit
-n/
-z test options). The only caveat is that you have to double quote the substitution or else it will probably error out on multi-word strings (too many arguments).
The bash/ksh
[[..]] extended test doesn't have that problem, by the way, and so is recommended.
http://mywiki.wooledge.org/BashFAQ/031