/commands/cmd/check-errorlevel-batch
Check %ERRORLEVEL% in a batch file (if errorlevel, ||, exit /b)
- tool
- Command Prompt (cmd)
- versions
- Windows 10, Windows 11, Windows Server 2016+
- os
- windows
After each command, cmd stores its exit code in the dynamic variable ERRORLEVEL. Read it with %ERRORLEVEL% right after the command, or test it with if errorlevel N, which is true when the code is N or higher. For a plain success/failure branch, command && echo ok || echo failed is shortest. End a batch file with exit /b N to return your own code to the caller.
The three ways to test it
findstr /c:"x" nul > nul
echo findstr on an empty input: %ERRORLEVEL%
if errorlevel 1 echo if errorlevel 1 is true for 1 or more
if %ERRORLEVEL% EQU 1 echo exactly 1
cmd /c exit 3
if errorlevel 1 echo exit 3 also passes if errorlevel 1
if errorlevel 4 (echo 4 or more) else (echo less than 4)
cmd /c exit 0 && echo success branch
cmd /c exit 5 || echo failure branchOutput
findstr on an empty input: 1 if errorlevel 1 is true for 1 or more exactly 1 exit 3 also passes if errorlevel 1 less than 4 success branch failure branch
| Test | True when | Notes |
|---|---|---|
| if %ERRORLEVEL% EQU 0 | code is exactly 0 | expanded when the line (or block) is parsed |
| if %ERRORLEVEL% NEQ 0 | code is not 0 | also catches negative codes |
| if errorlevel 1 | code >= 1 | does not catch negative codes |
| if not errorlevel 1 | code < 1 (0 or negative) | classic success test |
| cmd && a || b | a on 0, b otherwise | b also runs if a fails |
Inside parentheses, use delayed expansion
%ERRORLEVEL% is expanded once when cmd reads the whole ( ... ) block, so inside a block it shows the value from before the block. Use if errorlevel, or !ERRORLEVEL! with delayed expansion:
setlocal enabledelayedexpansion
cmd /c exit 0
(
cmd /c exit 2
echo percent form: %ERRORLEVEL%
echo delayed form: !ERRORLEVEL!
)Output
percent form: 0 delayed form: 2
Return a code from a batch file
call build.cmd
if errorlevel 1 exit /b %ERRORLEVEL%
echo build ok
exit /b 0exit /b N ends the batch file (or a call :label subroutine) and sets ERRORLEVEL to N for the caller; plain exit closes the whole cmd window. Use call other.cmd to run another batch file and come back; without call, control never returns.