Dos - Errorlevel (Error Handling|Exit Code)

About

exit code in DOS

Error Level

When errorlevel is:

  • = 0, then No Error occurred
  • > 0, then an error occurred

Example:

if %ERRORLEVEL% neq 0 (
  echo an error occurred
)
REM or
if %ERRORLEVEL% equ 0 (
  echo no error occurred
)

How to

Before ending script

if %ERRORLEVEL% neq 0 (
  exit /b %ERRORLEVEL%
)

where:

check it

You can test if with the if errorlevel statement:

  • bat files use one % to define a variable (By using 2 %, you will get then an error)
@echo off
for %%v in (*.bat) do echo %v
  • Running it cause this errors to occur:
error.bat
v was unexpected at this time
  • When you check the value of the ERRORLEVEL, you get:
echo %ERRORLEVEL%
9009
if errorlevel 9009 (echo bad variable initialization) else (echo that's all good)
bad variable initialization
  • But the default operator is not an equality but a “greater than”, then this “if” statement will also work
if errorlevel 9000 (echo a bad thing occurs) else (echo that's all good)
a bad thing occurs
if %errorlevel% EQU 9009 (echo the error 9009 occurs) else (echo the error 9009 doesn't occurs)
the error 9009 occurs

(reinitialize|reset) it

To reinitialize it to 0 after an error, you use the exit command with the B switch in a child batch script:

For instance, with the following script named: resetErrorLevel.bat

:: This script is there just to reset the error level
exit /B 0

If you start this demo script:

@echo off
echo Before the error, the errorlevel value is: %ERRORLEVEL%
copy badfile badlocation
echo After the error, the errorlevel value is: %ERRORLEVEL%
call resetErrorLevel.bat
echo After the resetErrorLevel.bat, the errorlevel value is %ERRORLEVEL%

you will get this output:

Before the error, the errorlevel value is: 0
The system cannot find the file specified.
After the error, the errorlevel value is: 1
After the resetErrorLevel.bat, the errorlevel value is 0

Powered by ComboStrap