使用批处理文件检查进程是否返回0
我想使用批处理文件启动一个进程,如果它返回非零,则执行其他操作。我需要正确的语法。
像这样的事情:
::x.bat
@set RetCode=My.exe
@if %retcode% is nonzero
handleError.exe
作为奖励,您可以考虑回答以下问题:)
- 如何使用
if
编写复合语句? - 如果应用程序
My.exe
由于缺少某些 DLL 而无法启动,我的 if 还能工作吗?如果没有,我如何检测My.exe
启动失败?
I want to start a process with a batch file and if it returns nonzero, do something else. I need the correct syntax for that.
Something like this:
::x.bat
@set RetCode=My.exe
@if %retcode% is nonzero
handleError.exe
As a bonus, you may consider answering the following questions, please :)
- How to write a compound statement with
if
? - If the application
My.exe
fails to start because some DLL is missing will my if work? If not, how can I detect thatMy.exe
failed to start?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
ERRORLEVEL
将包含最后一个命令的返回代码。遗憾的是,您只能检查>=
。请特别注意 MSDN 文档中
If
语句的这一行:因此,要检查 0,您需要跳出框框思考:
或者如果您想首先编写错误处理代码:
有关 BAT 编程的更多信息:http://www.ericphelps.com/batch/
或者更具体的 Windows
cmd
: MSDN 使用批处理文件ERRORLEVEL
will contain the return code of the last command. Sadly you can only check>=
for it.Note specifically this line in the MSDN documentation for the
If
statement:So to check for 0 you need to think outside the box:
Or if you want to code error handling first:
Further information about BAT programming: http://www.ericphelps.com/batch/
Or more specific for Windows
cmd
: MSDN using batch files您可以使用括号在 if 块中编写复合语句。第一个括号必须与 if 位于同一行,第二个括号单独位于一行。
You can write a compound statement in an if block using parenthesis. The first parenthesis must come on the line with the if and the second on a line by itself.
这并不完全是问题的答案,但每次我想了解当进程返回非零代码时如何让我的批处理文件退出并显示错误代码时,我都会在这里结束。
所以这是这个问题的答案:
This is not exactly the answer to the question, but I end up here every time I want to find out how to get my batch file to exit with and error code when a process returns an nonzero code.
So here is the answer to that:
我正在做的项目,我们做了类似的事情。我们使用
errorlevel
关键字,因此它看起来像:这似乎对我们有用。请注意,您可以在括号中输入多个命令,例如 echo 或其他命令。另请注意,build_fail 定义为:
The project I'm working on, we do something like this. We use the
errorlevel
keyword so it kind of looks like:That seems to work for us. Note that you can put in multiple commands in the parens like an echo or whatever. Also note that build_fail is defined as:
要检查进程/命令是否返回 0,请使用运算符
&& == 0 或
:not == 0||只需将运算符添加到您的脚本中:
To check whether a process/command returned 0 or not, use the operators
&& == 0 or
:not == 0||Just add operator to your script:
您可以使用下面的命令来检查它是否返回 0 或 1 :
在下面的示例中,我正在检查一个特定文件中的字符串,如果文件中不存在该特定单词“Error”(如果存在),则该字符串将为您提供 1然后 0
You can use below command to check if it returns 0 or 1 :
In below example, I am checking for the string in the one particular file which will give you 1 if that particular word "Error" is not present in the file and if present then 0