bash 如果 [$? -eq 0 ] 表示 shell 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7101995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does if [ $? -eq 0 ] mean for shell scripts?
提问by Oh Chin Boon
There is this line in a shell script i have seen:
我见过的 shell 脚本中有这一行:
grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null
if [ $? -eq 0 ]
回答by Chris Eberle
It's checking the return value ($?
) of grep
. In this case it's comparing it to 0 (success).
它正在检查 的返回值 ( $?
) grep
。在这种情况下,它将它与 0(成功)进行比较。
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
.
通常当你看到这样的东西(检查 grep 的返回值)时,它正在检查是否检测到特定的字符串。尽管/dev/null
不需要重定向到,但可以使用-q
.
回答by Wyzard
$?
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.
$?
是最近执行的命令的退出状态;按照惯例,0 表示成功,其他任何表示失败。该行正在测试grep
命令是否成功。
The grep
manpage states:
该grep
手册页指出:
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.)
如果找到选定的行,退出状态为 0,如果未找到,则退出状态为 1。如果发生错误,退出状态为 2。(注意:POSIX 错误处理代码应检查 '2' 或更大的值。)
So in this case it's checking whether any ERROR lines were found.
因此,在这种情况下,它会检查是否找到了任何 ERROR 行。
回答by William Pursell
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.)
(尽管在某些情况下您可以使用 'grep -q' 而不是重定向到 /dev/null,但这样做是不可移植的。grep 的许多实现不支持 -q 选项,因此如果您使用它,您的脚本可能会失败。 )