There is this line in a shell script i have seen:
grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null if [ $? -eq 0 ]
There is this line in a shell script i have seen:
grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null if [ $? -eq 0 ]
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
.
$?
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.
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 to fail if you use it.)