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?
EXIT /B at the end of the batch file will stop execution of a batch file. use EXIT /B < exitcodes > at the end of the batch file to return custom return codes. Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed.
Error Level. The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script.
Using EXIT /B will stop execution of a batch file or subroutine and return control to the command processor or to the calling batch file or code immediately. EXIT /B is available in Windows 2000 and later versions' CMD.
Batch file processing ends when execution reaches the end of the batch file. The trick therefore is to use the goto command to jump to a label right before the end of the file, so that execution “falls off the end”.
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.
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:
ERRORLEVEL
is defined then %errorlevel%
always resolves to its value (which can be arbitrary), and not to the current error level.%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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With