简体   繁体   English

从批处理文件中获取错误代码

[英]Get error code from within a batch file

我有一个运行几个可执行文件的批处理文件,我希望它成功退出,但是如果退出代码<> 0则停止。如何执行此操作?

Sounds like you'll want the "If Errorlevel" command. 听起来您会需要“ If Errorlevel”命令。 Assuming your executable returns a non-0 exit code on failure, you do something like: 假设您的可执行文件在失败时返回非零退出代码,则您可以执行以下操作:

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. 错误级别检查是作为大于等于检查进行的,因此任何非0的退出值都将触发跳转。 Therefore, if you need to check for more than one specific exit value, you should check for the highest one first. 因此,如果您需要检查多个特定的退出值,则应首先检查最高的退出值。

You can also use conditional processing symbols to do a simple success/failure check. 您还可以使用条件处理符号来进行简单的成功/失败检查。 For example: 例如:

myProgram.exe && echo Done!

would print Done! 会打印Done! only if myProgram.exe returned with error level 0. 仅当myProgram.exe返回错误级别为0时。

myProgram.exe || PAUSE

would cause the batch file to pause if myProgram.exe returns a non-zero error level. 如果myProgram.exe返回非零错误级别,将导致批处理文件暂停。

A solution better than Hellion's answer is 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. 命令IF ERRORLEVEL 1 ...负返回值。 Some progrmas may also use negative values to indicate error. 一些程序可能还会使用负值来指示错误。

BTW, I love Cheran's answer (using && and || operators), and recommend that to all. 顺便说一句,我喜欢Cheran的答案 (使用&&||运算符),并向所有人推荐。

For more information about the topic, read this article 有关该主题的更多信息,请阅读本文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM