windows 从批处理文件中获取错误代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3452046/
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
Get error code from within a batch file
提问by Dlongnecker
I have a batch file that runs a couple executables, and I want it to exit on success, but stop if the exit code <> 0. How do I do this?
我有一个运行几个可执行文件的批处理文件,我希望它在成功时退出,但如果退出代码 <> 0 则停止。我该怎么做?
回答by Hellion
Sounds like you'll want the "If Errorlevel" command. Assuming your executable returns a non-0 exit code on failure, you do something like:
听起来您需要“If Errorlevel”命令。假设您的可执行文件在失败时返回非 0 退出代码,您可以执行以下操作:
myProgram.exe
if errorlevel 1 goto somethingbad
echo Success!
exit
:somethingbad
echo Something Bad Happened.
Errorlevel checking is done as a greater-or-equal check, so any non-0 exit value will trigger the jump. Therefore, if you need to check for more than one specific exit value, you should check for the highest one first.
错误级别检查是作为大于或等于检查完成的,因此任何非 0 退出值都将触发跳转。因此,如果您需要检查多个特定退出值,则应首先检查最高的一个。
回答by Cheran Shunmugavel
You can also use conditional processing symbolsto do a simple success/failure check. For example:
您还可以使用条件处理符号进行简单的成功/失败检查。例如:
myProgram.exe && echo Done!
would print Done!
only if myProgram.exe
returned with error level 0.
Done!
仅在myProgram.exe
以错误级别 0 返回时才打印。
myProgram.exe || PAUSE
would cause the batch file to pause if myProgram.exe returns a non-zero error level.
如果 myProgram.exe 返回非零错误级别,则会导致批处理文件暂停。
回答by Mohammad Dehghan
A solution better than Hellion's answeris checking the %ERRORLEVEL%
environment variable:
比Hellion 的答案更好的解决方案是检查%ERRORLEVEL%
环境变量:
IF %ERRORLEVEL% NEQ 0 (
REM do something here to address the error
)
It executes the IF
body, if the return code is anything other than zero, not just values greater than zero.
IF
如果返回代码不是零,而不仅仅是大于零的值,它就会执行主体。
The command IF ERRORLEVEL 1 ...
misses the negative return values. Some progrmas may also use negative values to indicate error.
该命令IF ERRORLEVEL 1 ...
错过了负返回值。一些程序也可能使用负值来表示错误。
BTW, I love Cheran's answer(using &&
and ||
operators), and recommend that to all.
顺便说一句,我喜欢Cheran 的回答(使用&&
和||
运算符),并向所有人推荐。
For more information about the topic, read this article
有关该主题的更多信息,请阅读这篇文章