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

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

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

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

回答1:

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.



回答2:

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



回答3:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!