Getting a Simple True/False from a Search
Problem
You need to know whether a certain string is in a particular file. However, you don’t want any output, just a yes or no sort of answer.
Solution
Use -q, the “quiet” option for grep. Or, for maximum
portability, just throw the output away by redirecting it into /dev/null. Either way, your
answer is in the bash return status variable $? so
you can use it in an if-test like
this:
$ grep -q findme bigdata.file $ if [ $? -eq 0 ] ; then echo yes ; else echo nope ; fi nope $
Discussion
In a shell script, you often don’t want the results of the search displayed in the out-put; you just want to know whether there is a match so that your script can branch accordingly.
As with most Unix/Linux commands, a return value of 0 indicates successful completion. In this case, success is
defined as having found the string in at least one of the given files
(in this example, we searched in only one file). The return value is
stored in the shell variable $?, which we can then use in an if statement.
If we list multiple filenames after grep
-q, then grep stops searching after the
very first occurrence of the search string being found. It doesn’t
search all the files, as you really just want to know whether it found
any occurrence of the string. If you really need to read through all the
files (why?), then rather than use -q
you can do this:
$ grep findme bigdata.file > /dev/null $ if [ $? -eq 0 ] ; then echo yes ; else echo nope ; fi nope $
The redirecting to
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access