48

There is this line in a shell script i have seen:

grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME}  > /dev/null
if [ $? -eq 0 ] 
3
  • 1
    thanks Wyzard and Chris, great answers, however i may only select one answer. ><
    – HJW
    Aug 18, 2011 at 3:51
  • This question was asked and answered on August 18, 2011, but is being closed as being similar to a question asked and answered on August 30, 2011. Why are we allowing this o_o. Please upvote to keep this Open
    – HJW
    Dec 3, 2020 at 8:31
  • Is there any good reason to keep this open, like: is there any difference to the other question?
    – Nico Haase
    Dec 3, 2020 at 14:57

3 Answers 3

47

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded.

The grep manpage states:

The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.)

So in this case it's checking whether any ERROR lines were found.

0
44

It's checking the return value ($?) of grep. In this case it's comparing it to 0 (success).

Usually when you see something like this (checking the return value of grep) it's checking to see whether the particular string was detected. Although the redirect to /dev/null isn't necessary, the same thing can be accomplished using -q.

3
  • One question, where is /dev/null and what is it? Is it a file?
    – HJW
    Aug 18, 2011 at 3:53
  • 6
    /dev/null is a kind of special "black hole" file. When you write to it, the data is thrown away. It's a classic way of stopping a program from printing its output to the screen. Aug 18, 2011 at 4:07
  • To add to @Chris comment, /dev/null means "null device". When I think about what /dev/null actually is, it doesn't seem like such a great choice for a username. Aug 18, 2011 at 17:24
4

It is an extremely overused way to check for the success/failure of a command. Typically, the code snippet you give would be refactored as:

if grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null; then
   ...
fi

(Although you can use 'grep -q' in some instances instead of redirecting to /dev/null, doing so is not portable. Many implementations of grep do not support the -q option, so your script may fail if you use it.)

Not the answer you're looking for? Browse other questions tagged or ask your own question.