Error level
suggest changeCommands usually set error level at the end of their execution. In Windows NT and later, it is a 32-bit signed integer; in MS DOS, it used to be an integer from 0 to 255. Keywords: return code, exit code, exit status.
The conventional meaning of the error level:
- 0 - success
- not 0 - failure
- The error levels being set are usually positive.
- If the command does not distinguish various kinds of failure, the error level on failure is usually 1.
Uses of the error level:
- It can be tested using
&&
and||
; see also syntax. - It can be tested using IF.
- The value can be accessed from
ERRORLEVEL
variable.
Examples:
dir >NUL && echo Success
- The part after && is executed only if the error level is zero.
color 00 || echo Failure
- The part after || is executed only if the error level is non-zero, whether positive or negative.
color 00 || ( echo Failure)
- Multi-line bracketing works as well.
echo %ERRORLEVEL%
- Displays the error level without changing it.
if %errorlevel% equ 0 echo The error level is zero, meaning success.
if %errorlevel% neq 0 echo The error level is non-zero, meaning failure.
if errorlevel 1 echo The error level is >= 1, meaning failure via positive error level.
- Does not cover failure via negative error level. Note the
>=
part: this is not the same asif %errorlevel% equ 1
.
- Does not cover failure via negative error level. Note the
exit /b 1
- Returns a batch file, setting the error level to 1.
cmd /c "exit /b 10"
- In the middle of a batch file or on the command line, sets the error level to 10.
(cmd /c "exit /b 0" && Echo Success) & (cmd /c "exit /b -1" || Echo Failure)
- As above, showing the error level is indeed affected.
(cmd /c "exit /b 0" & cmd /c "exit /b 1") || Echo Failure
- The error level of a chain created by
&
is the error level of the last command of the chain.
- The error level of a chain created by
cmd /c "exit /b -1" & if not errorlevel 1 echo Would-be success
- The
if not errorlevel 1
test, which might appear to test for success, passes on negative numbers: it tests on "not error level >= 1", which is "error level <= 0".
- The
set myerrorlevel=%errorlevel%
- Remembers the error level for later.
set errorlevel=0
- To be avoided: overshadows the built-in
errorlevel
variable. Ensures that subsequent accesses via%ERRORLEVEL%
return 0 rather than the actual error level.
- To be avoided: overshadows the built-in
cmd /c "exit /b 0"if 1 equ 1 ( cmd /c "exit /b 1" & echo %errorlevel% )
- Displays 0, since
%errorlevel%
gets expanded beforecmd /c "exit /b 1"
gets executed.
- Displays 0, since
Links:
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents