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 ] 
Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215
  • 1
    thanks Wyzard and Chris, great answers, however i may only select one answer. > – Oh Chin Boon Aug 18 '11 at 03: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 – Oh Chin Boon Dec 03 '20 at 08:31
  • Is there any good reason to keep this open, like: is there any difference to the other question? – Nico Haase Dec 03 '20 at 14:57

3 Answers3

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.

Wyzard
  • 33,849
  • 3
  • 67
  • 87
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.

Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
  • One question, where is /dev/null and what is it? Is it a file? – Oh Chin Boon Aug 18 '11 at 03: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. – Chris Eberle Aug 18 '11 at 04: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. – Daniel Haley Aug 18 '11 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.)

William Pursell
  • 204,365
  • 48
  • 270
  • 300