使用“EXIT/B X"退出批处理,其中 X>=1 就像在使用 && 时命令成功完成一样.或 ||批处理调用之间的运算符 [英] Exiting batch with `EXIT /B X` where X>=1 acts as if command completed successfully when using && or || operators between batch calls
问题描述
我正在尝试使用 EXIT/BX
命令链接一系列 .bat 文件以返回成功或失败以及 &&
和 ||
用于下一个 .bat 的条件运行(例如 a.bat && b.bat
).
I'm trying to chain a series of .bat files using the EXIT /B X
command to return success or failure and &&
and ||
for conditional running of the next .bat (e.g. a.bat && b.bat
).
无论我是调用 EXIT/B 0
还是其他任何东西来结束 a.bat,a.bat &&b.bat
之后会调用 b.bat.我的理解是 EXIT/B 0
应该设置 ERRORLEVEL=0
,这是成功的,所以 &&
应该继续.与此相反的是,调用 EXIT/B 1
应该设置 ERRORLEVEL=1
失败,所以 &&
应该停止.我在这里错过了什么?
Regardless of whether I call EXIT /B 0
or anything else to end a.bat, a.bat && b.bat
will call b.bat afterward. My understanding is that EXIT /B 0
should set ERRORLEVEL=0
, which is success, so the &&
should continue. The counterpoint to this is that calling EXIT /B 1
should set ERRORLEVEL=1
which is failure, so the &&
should stop. What am I missing here?
简单的例子:
对于非批处理命令,按预期执行:
For non-batch commands, acting as expected:
C:> echo test|findstr test>NUL && echo yes
yes
C:> echo test|findstr test>NUL || echo yes
C:> echo test|findstr nope>NUL && echo yes
C:> echo test|findstr nope>NUL || echo yes
yes
使用 EXIT/B
总是看到 a.bat 成功:
Using EXIT /B
always sees a.bat as successful:
C:> echo @EXIT /B 0 > a.bat
C:> a.bat && echo yes
yes
C:> a.bat || echo yes
C:> echo @EXIT /B 1 > a.bat
C:> a.bat && echo yes
yes
C:> a.bat || echo yes
如何退出 a.bat 以便 a.bat &&b.bat
和 a.bat ||b.bat
行为是否符合预期?
How can I exit from a.bat so that a.bat && b.bat
and a.bat || b.bat
behave as expected?
所有命令都在 Windows XP SP3 上的 cmd.exe 中运行.
All commands are run in cmd.exe on Windows XP SP3.
推荐答案
如果您问我,批处理文件中的退出代码正是出于这个原因而损坏的,但是您可以使用一种非常巧妙的解决方法.作为批处理文件的最后一行,使用:
If you ask me, exit codes in batch files are broken for this exact reason, but there is a hacky workaround you can use. As the last line of your batch file, use:
@%COMSPEC% /C exit 1 >nul
由于这是一个实际启动的进程,因此您会得到一个真正的进程退出代码和 &&和 ||会工作.
Since this is an actual process that is started you get a real process exit code and && and || will work.
这篇关于使用“EXIT/B X"退出批处理,其中 X>=1 就像在使用 && 时命令成功完成一样.或 ||批处理调用之间的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!