Search code examples
batch-filecmderrorlevel

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


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.


Solution

  • 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