Skip to content

/commands/cmd/check-errorlevel-batch

Check %ERRORLEVEL% in a batch file (if errorlevel, ||, exit /b)

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated
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

cmd
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 branch

Output

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
TestTrue whenNotes
if %ERRORLEVEL% EQU 0code is exactly 0expanded when the line (or block) is parsed
if %ERRORLEVEL% NEQ 0code is not 0also catches negative codes
if errorlevel 1code >= 1does not catch negative codes
if not errorlevel 1code < 1 (0 or negative)classic success test
cmd && a || ba on 0, b otherwiseb 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:

cmd
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

deploy.cmd
call build.cmd
if errorlevel 1 exit /b %ERRORLEVEL%
echo build ok
exit /b 0

exit /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.

Sources