Why does cmd.exe have different errorlevel behavior on a 64-bit machine?

ε祈祈猫儿з 提交于 2019-12-06 04:53:17

问题


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.


回答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 file




回答2:


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.



来源:https://stackoverflow.com/questions/1924497/why-does-cmd-exe-have-different-errorlevel-behavior-on-a-64-bit-machine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!