-
In Windows Batch scripting,
ERRORLEVELis used to check the exit code of the last executed command or program.It's a critical tool for error handling and control flow, especially in automation, scripting pipelines, or conditionally executing code.
-
ERRORLEVELis an environment variable that stores the exit code of the last run program or script. -
Most commands and utilities in Windows return an exit code:
0usually means success- Any other number (e.g.,
1,2,9009, etc.) indicates some kind of failure
@ECHO OFF DIR "C:\Some\Fake\Path" ECHO Last exit code was: %ERRORLEVEL%
- If the path doesn't exist,
%ERRORLEVEL%will be non-zero.
Code Meaning 0 Success 1 General error 2 Incorrect usage / syntax 9009 Command not found The
IF ERRORLEVELsyntax is a bit non-intuitive for beginners:IF ERRORLEVEL n command
This checks if
%ERRORLEVEL%is greater than or equal ton, not just equal ton.IF ERRORLEVEL 1
means:
IF %ERRORLEVEL% GEQ 1So, if
%ERRORLEVEL%is 5, the condition will still match!
-
-
@ECHO OFF COPY file.txt D:\backup\ IF ERRORLEVEL 1 ( ECHO Copy failed! ) ELSE ( ECHO Copy succeeded. )
-
If you want to check for a specific code, use descending order:
@ECHO OFF SomeCommand IF ERRORLEVEL 3 ( ECHO Exit code was 3 or more ) ELSE IF ERRORLEVEL 2 ( ECHO Exit code was 2 or more ) ELSE IF ERRORLEVEL 1 ( ECHO Exit code was 1 or more ) ELSE ( ECHO Exit code was 0 )
☑️ Always list the highest values first due to the
GEQbehavior. -
Use
EXIT /B [number]to set your own error code inside a script or subroutine:@ECHO OFF CALL :Check 0 CALL :Check 1 GOTO :EOF :Check ECHO Checking with exit code %1 EXIT /B %1
Then use
%ERRORLEVEL%orIF ERRORLEVELto control behavior based on the result.
| Tip | Why |
|---|---|
Use IF ERRORLEVEL in descending order |
Prevents multiple matches |
Use EXIT /B n in subroutines |
To simulate return codes |
Reset %ERRORLEVEL% if needed |
Some commands (like SET) don’t reset it |
Combine with ` and&&` for simpler flow |
Reduces nested blocks |
SomeCommand && ECHO Success || ECHO Failed&&runs the next command only if the previous succeeded (ERRORLEVEL = 0)||runs the next command only if the previous failed (ERRORLEVEL > 0)
This behaves like a shorthand IF ERRORLEVEL check.
| Concept | Usage Example | Notes |
|---|---|---|
| Check exit code ≥ n | IF ERRORLEVEL 2 |
GEQ behavior |
| Exact code check | Descending IF ERRORLEVEL blocks |
Recommended |
| View current error | ECHO %ERRORLEVEL% |
Shows last result |
| Set custom code | EXIT /B 3 |
Manual control |
| Short condition | `cmd && echo OK | echo Fail` |