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 /dev/null sends the output to a special kind of device, a bit bucket, that just throws everything you give it away.

The /dev/null technique is also useful if you want to write shell scripts that are portable across the various flavors of grep that are available on Unix and Linux systems, should you find one that doesn’t support the -q option.

See Also

  • man grep

  • man regex (Linux, Solaris, HP-UX) or man re_format (BSD, Mac) for the details of your regular expression library

  • Mastering Regular Expressions by Jeffrey E. F. Friedl (O’Reilly)

  • Expecting to Change Exported Variables

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.130.24