Windows batch exit option b with or without errorlevel
Asked Answered
E

1

8

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?

Exacerbate answered 11/6, 2014 at 8:59 Comment(0)
S
7

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.

Shreve answered 11/6, 2014 at 9:6 Comment(1)
The last item could be solved by enabling and applying delayed variable expansion using copy j:\not_existing q:\not_existing & echo !errorlevel!Swept

© 2022 - 2024 — McMap. All rights reserved.