views:

407

answers:

2

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  A: 

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

Anders
Excellent, I tried your suggestion and it works the same on both machines.
paraquat
A: 

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.

Isaac Rabinovitch