Immediately after a command exits, its exit code is stored in the special variable "$?
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
constructs are actually working with. So you can replace it with just about any command if you want.
if grep -q 'foobar' file.txt ; then
echo 'string found in file'
echo 'string not found in file'
, 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
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.