jwchoi
jwchoi

Reputation: 737

Windows batch exit option b with or without errorlevel

I'm newbie in using batch on Windows and have a question about the use of errorlevel.

I referenced TechNet(Exit) and many examples on google.

Most of them used /b with %errorlevel% like this

if errorlevel 1 exit /b %errorlevel%

I wonder the difference between

if errorlevel 1 exit /b

and

if errorlevel 1 exit /b %errorlevel%

I think there are no difference because %errorlevel% is not changed. Am I wrong?

Upvotes: 8

Views: 8289

Answers (2)

himself
himself

Reputation: 4884

Unfortunately it seems exit /B does not always work as you would expect from exit /B %ERRORLEVEL%. If you're on the topmost level of the batch file, then both commands will close the cmd.exe (assuming it's configured to be closed), but exit /B will not convert the error level to its return code.

Example:

test.cmd:

@echo off
cmd /C "exit /B 1"
echo %ERRORLEVEL%
exit /B

Run:

> cmd /C "test.cmd"
1
> echo %ERRORLEVEL%
0

Meanwhile exit /B %ERRORLEVEL% sets the return code just fine.

This makes exit /B unreliable, unfortunately, for batch files which can be called standalone (scheduled tasks and other such things).

Upvotes: 0

Jon
Jon

Reputation: 437326

TL;DR

Most of the time there should be no difference, but technically exit /b %errorlevel% is strictly worse than exit /b if what you want is to exit without changing the error level.

Analysis

EXIT /B without the optional errorlevel parameter does not change the error level, so as a standalone command it is exactly equivalent to EXIT /B %errorlevel% provided that %errorlevel% resolves to the current error level.

But there are cases where it might not do so:

  • If an environment variable named ERRORLEVEL is defined then %errorlevel% always resolves to its value (which can be arbitrary), and not to the current error level.
  • If command extensions are disabled then %errorlevel% will never resolve to the current error level (it will still read the value of the environment variable with that name, if defined). You can verify this by starting a command prompt with CMD /E:OFF and trying ECHO %errorlevel%.
  • The current error level value as produced by %errorlevel% will be fixed at the time the command is parsed, not at the time execution reaches that expression. This can result in the wrong value being produced for more complex commands. Example:

    copy j:\not_existing q:\not_existing & echo %errorlevel%
    

    This will not produce the same result as

    copy j:\not_existing q:\not_existing
    echo %errorlevel%
    

    because in the first case %errorlevel% will not produce the updated error level caused by the failed copy.

Upvotes: 7

Related Questions