[bash] What does if [ $? -eq 0 ] mean for shell scripts?

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

grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME}  > /dev/null
if [ $? -eq 0 ] 

This question is related to bash shell

The answer is


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.)


$? 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.