为什么 cmd.exe 在 64 位计算机上具有不同的错误级别行为?
例如,如果我制作一个名为 temp.bat 的批处理脚本,其中包含:
exit /b 1
当我以各种方式运行它时,我在 32 位 XP 系统和 64 位 XP 系统上会得到不同的行为。
在 32 位上:
> temp.bat
> echo %ERRORLEVEL%
1
> cmd /c temp.bat
> echo %ERRORLEVEL%
0
在 64 位上:
> temp.bat
> echo %ERRORLEVEL%
1
> cmd /c temp.bat
> echo %ERRORLEVEL%
1
我搜索了 cmd.exe 选项,但找不到任何控制它如何从批处理脚本传播错误级别信息的选项。目前我无法为这种差异找到任何合理的解释。
If I make a batch script named temp.bat (for example) containing:
exit /b 1
When I run it in various ways, I get different behavior on my 32-bit XP system vs. a 64-bit XP system.
On 32-bit:
> temp.bat
> echo %ERRORLEVEL%
1
> cmd /c temp.bat
> echo %ERRORLEVEL%
0
On 64-bit:
> temp.bat
> echo %ERRORLEVEL%
1
> cmd /c temp.bat
> echo %ERRORLEVEL%
1
I've searched through the cmd.exe options and I have been unable to find any options controlling how it propagates errorlevel information from batch scripts. At this point I'm unable to find any rational explanation for this difference.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须小心 exit /b,因为它实际上并不在所有情况下都能正常工作。例如:
temp.bat&&echo 0||echo 1
如果 temp.bat 包含 exit /b 1,您会期望打印 1,但事实并非如此。遗憾的是,真正为批处理文件设置工作退出代码的唯一方法是使用
@%COMSPEC% /C exit 1
作为批处理文件中的最后行You have to be careful with exit /b since it does not actually work correctly in all instances. For example:
temp.bat&&echo 0||echo 1
If temp.bat contains exit /b 1 you would expect 1 to be printed, but it is not. Sadly, the only way to really set a working exit code for a batch file is to use
@%COMSPEC% /C exit 1
as the last line in the batch fileAnders 示例的问题在于它使用了 .bat 文件。如果您使用 .cmd 文件,退出将按照记录进行。
同时拥有 .bat 和 .cmd 文件的要点似乎是向后兼容性:如果它正在执行 .bat 文件,cmd 会尝试模拟 NT 之前的 CLI,command.com,它的错误处理要简单得多。
至少这是我的猜测。我在谷歌搜索有关 .bat/.cmd 的官方文档时偶然发现了这个线程,但我似乎找不到。
The problem with Anders's example is that it uses a .bat file. If you use a .cmd file, exit works as documented.
The main point of having both .bat and .cmd files seems to be backward compatibility: if it's executing a .bat file, cmd tries to emulate the pre-NT CLI, command.com, which had much simpler error handling.
At least that's my surmise. I stumbled on this thread while googling for official docs on the .bat/.cmd thing, which I can't seem to find.