Every command or application returns an exit status, also known as a return status or exit code.
A successful command or application returns a 0
, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code.
In Linux you can get the exit status of a last command by executing echo $?
.
In this article i will show how to get the return code from the last console command or application in Windows using the command-line prompt (CMD) or the PowerShell.
Exit Code Of Last Console Command
Return True
or False
depending on whether the last console command or application exited without error or not:
# Windows CMD C:\> if %ErrorLevel% equ 0 (echo True) else (echo False) # Windows PowerShell PS C:\> $?
Get the exit code of the last console command or application:
# Windows CMD C:\> echo %ErrorLevel% # Windows PowerShell PS C:\> $LastExitCode
Exit Code Of Windowed Application
Return True
or False
depending on whether the last windowed application exited without error or not:
# Windows CMD C:\> start /wait app.exe C:\> if %ErrorLevel% equ 0 (echo True) else (echo False) # Windows PowerShell PS C:\> app.exe PS C:\> $?
Get the exit code of the windowed application:
# Windows CMD C:\> start /wait app.exe C:\> echo %ErrorLevel% # Windows PowerShell PS C:\> app.exe PS C:\> $LastExitCode
Was it useful? Share this post with the world!
- Overview
- Part 1 – Getting Started
- Part 2 – Variables
- Part 3 – Return Codes
- Part 4 – stdin, stdout, stderr
- Part 5 – If/Then Conditionals
- Part 6 – Loops
- Part 7 – Functions
- Part 8 – Parsing Input
- Part 9 – Logging
- Part 10 – Advanced Tricks
Today we’ll cover return codes as the right way to communicate the outcome of your script’s execution to the world. Sadly, even
skilled Windows programmers overlook the importance of return codes.
Return Code Conventions
By convention, command line execution should return zero when execution succeeds and non-zero when execution fails. Warning messages
typically don’t effect the return code. What matters is did the script work or not?
Checking Return Codes In Your Script Commands
The environmental variable %ERRORLEVEL%
contains the return code of the last executed program or script. A very helpful feature is
the built-in DOS commands like ECHO
, IF
, and SET
will preserve the existing value of %ERRORLEVEL%
.
The conventional technique to check for a non-zero return code using the NEQ
(Not-Equal-To) operator of the IF
command:
IF %ERRORLEVEL% NEQ 0 (
REM do something here to address the error
)
Another common technique is:
IF ERRORLEVEL 1 (
REM do something here to address the error
)
The ERRORLEVEL 1
statement is true when the return code is any number equal to or greater than 1. However, I don’t use this technique because
programs can return negative numbers as well as positive numbers. Most programs rarely document every possible return code, so I’d rather explicity
check for non-zero with the NEQ 0
style than assuming return codes will be 1 or greater on error.
You may also want to check for specific error codes. For example, you can test that an executable program or script is in your PATH by simply
calling the program and checking for return code 9009.
SomeFile.exe
IF %ERRORLEVEL% EQU 9009 (
ECHO error - SomeFile.exe not found in your PATH
)
It’s hard to know this stuff upfront – I generally just use trial and error to figure out the best way to check the return code of the program or
script I’m calling. Remember, this is duct tape programming. It isn’t always pretty, but, it gets the job done.
Conditional Execution Using the Return Code
There’s a super cool shorthand you can use to execute a second command based on the success or failure of a command. The first program/script must
conform to the convention of returning 0 on success and non-0 on failure for this to work.
To execute a follow-on command after sucess, we use the &&
operator:
SomeCommand.exe && ECHO SomeCommand.exe succeeded!
To execute a follow-on command after failure, we use the ||
operator:
SomeCommand.exe || ECHO SomeCommand.exe failed with return code %ERRORLEVEL%
I use this technique heavily to halt a script when any error is encountered. By default, the command processor will continue executing
when an error is raised. You have to code for halting on error.
A very simple way to halt on error is to use the EXIT
command with the /B
switch (to exit the current batch script context, and not the command
prompt process). We also pass a specific non-zero return code from the failed command to inform the caller of our script about the failure.
SomeCommand.exe || EXIT /B 1
A simliar technique uses the implicit GOTO label called :EOF
(End-Of-File). Jumping to EOF in this way will exit your current script with
the return code of 1.
SomeCommand.exe || GOTO :EOF
Tips and Tricks for Return Codes
I recommend sticking to zero for success and return codes that are positive values for DOS batch files. The positive values are a good idea
because other callers may use the IF ERRORLEVEL 1
syntax to check your script.
I also recommend documenting your possible return codes with easy to read SET
statements at the top of your script file, like this:
SET /A ERROR_HELP_SCREEN=1
SET /A ERROR_FILE_NOT_FOUND=2
Note that I break my own convention here and use uppercase variable names – I do this to denote that the variable is constant and should not
be modified elsewhere. Too bad DOS doesn’t support constant values like Unix/Linux shells.
Some Final Polish
One small piece of polish I like is using return codes that are a power of 2.
SET /A ERROR_HELP_SCREEN=1
SET /A ERROR_FILE_NOT_FOUND=2
SET /A ERROR_FILE_READ_ONLY=4
SET /A ERROR_UNKNOWN=8
This gives me the flexibility to bitwise OR multiple error numbers together if I want to record numerous problems in one error code.
This is rare for scripts intended for interactive use, but, it can be super helpful when writing scripts you support but you don’t
have access to the target systems.
@ECHO OFF
SETLOCAL ENABLEEXTENSIONS
SET /A errno=0
SET /A ERROR_HELP_SCREEN=1
SET /A ERROR_SOMECOMMAND_NOT_FOUND=2
SET /A ERROR_OTHERCOMMAND_FAILED=4
SomeCommand.exe
IF %ERRORLEVEL% NEQ 0 SET /A errno^|=%ERROR_SOMECOMMAND_NOT_FOUND%
OtherCommand.exe
IF %ERRORLEVEL% NEQ 0 (
SET /A errno^|=%ERROR_OTHERCOMMAND_FAILED%
)
EXIT /B %errno%
If both SomeCommand.exe and OtherCommand.exe fail, the return code will be the bitwise combination of 0x1 and 0x2, or decimal 3. This return code tells
me that both errors were raised. Even better, I can repeatedly call the bitwise OR with the same error code and still interpret which errors were
raised.
<< Part 2 – Variables
Part 4 – stdin, stdout, stderr >>
Last Updated :
27 Jan, 2022
Return codes are the codes returned by programs when they are executed. If the command line is successful, it should return zero; if it is not successful, it should return non-zero. If the test fails, a non-zero value indicates the error number, and the user can attempt to resolve it by navigating to the error message.
The test may also return an exit code. A program’s or utility’s exit code usually appears when it finishes or terminates.
The list below includes some of the non-zero exit codes (with their respective errors) that programs may return
Error Code | Description |
---|---|
0 | Successful completion of the program. |
1 | This error indicates that the Windows command prompt has attempted to execute an unrecognized action |
2 | An error indicating that the file could not be found in the specified location |
3 | An error message indicated that the specified path could not be found. |
5 | An indication that the user is not authorized to access the resource |
90090×2331 | This error occurs when you misspell the command, application name, or path when configuring an Action. |
2212254950xC0000017-1073741801 | The error message tells you that Windows has run out of memory. |
32212257860xC000013A-1073741510 | This indicates that the user terminated the application |
32212257940xC0000142-1073741502 | The message indicating that the application was launched on a desktop to which the current user doesn’t have access |
Batch file error level:
%ERRORLEVEL% is an environment variable that contains the last error level or return code in the batch file — that is, the last error code of the last command executed. Error levels may be checked by using the %ERRORLEVEL% variable as follows:
IF %ERRORLEVEL% NEQ 0 ( DO_Something )
A common method of returning error codes from batch files is to use the command EXIT /B %ERRORLEVEL%.
For custom return codes, use the EXIT /B <exitcodes> command.
Example:
In the below example, if the condition is met, the script will terminate with the exit code 0. If the condition isn’t met, then the exit code will be 1.
if [[ "$(whoami)" != root ]]; then echo "Not root user." exit 1 fi echo "root user" exit 0
Output:
Loops:
There have been statements enacted sequentially in the decision-making chapter. Alternatively, Batch Script can also be used to alter the flow of control in a program’s logic. These statements are then organized into flow control statements.
Serial No | Loops | Description |
---|---|---|
1 | While Statement Implementation | There is no direct while statement in Batch Script, although labels and an if statement can be used to implement this loop. |
2 | For Statement — List Implementations | Batch files can loop using the «FOR» construct. In order to work with a list of values, the ‘for’ statement requires the following construct. |
3 | Looping through Ranges | ‘For’ statements can also move through ranges of values. A general version is presented below. |
4 | Classic for Loop Implementation | It has the classic ‘for’ statement found in many programming languages. |
5 | Break Statement Implementation | Within any programming language, the break statement is used to alter the flow of control inside a loop. As part of looping constructs, the break statement causes the innermost enclosing loop to terminate immediately |
Looping through Command Line Arguments
For checking command-line arguments, you can use the for statement. Here is an example of how to loop through the arguments of a command line using the ‘for’ statement.
for ((c=1; c<=7; c++)) do echo "Welcome $c times" done
Output:
Windows CMD exit codes indicate the success or failure of a command or script, providing a numeric status that can be used for error handling in batch files or scripts.
Here’s an example of checking the exit code after running a command:
echo off
your_command_here
if %errorlevel% neq 0 (
echo Command failed with exit code %errorlevel%
) else (
echo Command succeeded with exit code %errorlevel%
)
What Are Exit Codes?
Definition of Exit Codes
Windows CMD exit codes are numerical values returned by a command or script upon its completion. These codes provide insight into whether a command was successful or whether it encountered errors. Understanding exit codes is essential for diagnosing problems and improving the efficiency of your command-line operations.
Standard Exit Code Values
In CMD, exit codes typically adhere to a few standard values:
- 0: Indicates that the command was successful without any errors. This is the exit code of success.
- 1: Represents a general error. This code suggests that something went wrong, but it doesn’t specify the exact issue.
- Common Codes (2-255): Various other codes may indicate specific types of errors or warnings based on the command executed. Familiarity with these can greatly aid troubleshooting.
Mastering Windows Cmd Switches: A Concise Guide
How to Use Exit Codes in CMD
Basic Syntax for Checking Exit Codes
To check the exit code after running a command, you can use the built-in variable `%ERRORLEVEL%`. This variable holds the exit code of the last command executed. Here’s the basic syntax:
command
echo %ERRORLEVEL%
This simple approach allows you to receive immediate feedback on the success or failure of any command you’ve run.
Understanding Common CMD Commands and Their Exit Codes
Different commands in CMD can have their unique expected exit codes. Understanding these can help you troubleshoot effectively:
- COPY: The `COPY` command is used to copy files. A successful copy returns an exit code of 0, while a failure (like a non-existent source file) results in 1.
- DEL: The `DEL` command deletes files. Similar to `COPY`, success returns 0, and failure returns 1. If you try to delete a file that does not exist, you’ll receive an appropriate error code.
- PING: Used for testing network connections. A successful ping returns 0, while unreachable targets will return 1.
Windows Cmd Clear: Refresh Your Command Line Effortlessly
Practical Examples of Exit Codes
Example 1: A Simple File Copy Operation
When you execute a command to copy a file, it’s helpful to check the exit code to verify that the operation was successful.
copy file.txt destination.txt
echo %ERRORLEVEL%
If the copy command succeeds, the output will display 0. If `file.txt` doesn’t exist, you will get an exit code of 1, indicating an error.
Example 2: Deleting a Non-Existent File
Attempting to delete a file that does not exist will also provide valuable insight into how CMD handles errors.
del nonexistentfile.txt
echo %ERRORLEVEL%
In this case, you should see an exit code of 1, signaling that the file couldn’t be deleted because it was never there in the first place.
Example 3: Using PING Command to Check Connectivity
The `PING` command is a practical and frequently used command to test network availability.
ping google.com
echo %ERRORLEVEL%
If you receive a successful response from Google, the exit code will be 0. If your internet connection is down or Google is unreachable, you will receive an error code of 1, indicating a failed connection.
Mastering Windows Cmd Route: A Concise Guide
Custom Exit Codes in Batch Files
Creating a Batch File with Custom Exit Codes
You have the ability to create custom exit codes in batch files, which can help streamline error handling and troubleshooting in your scripts. Consider the example below:
@echo off
if exist myfile.txt (
exit /b 0
) else (
exit /b 1
)
In this script, if `myfile.txt` exists, the script exits with a code of 0. If it does not exist, it exits with a code of 1.
Best Practices for Using Exit Codes in Scripts
Using meaningful exit codes in your scripts enhances both clarity and usability. Documenting your exit codes helps not only you but also others who may use or modify your code in the future. Consider establishing a standard to ensure consistency across your scripts.
Windows Cmd Repair Commands: A Quick Guide
Troubleshooting Common Exit Code Issues
Diagnosing Problems Using Exit Codes
Interpreting exit codes is a crucial skill for troubleshooting. By analyzing the return value of commands, you can pinpoint specific issues, whether it’s syntax errors, unavailable files, or other problems.
Logging and Monitoring Exit Codes
Setting up logging to capture exit codes during script execution can be immensely beneficial for debugging. By saving exit codes to a log file, you can track the history of your script’s operation and quickly identify which parts may be failing. Consider using tools or frameworks designed for logging CMD operations for a more organized approach.
Mastering Windows Cmd Remote Desktop: Quick Command Guide
Conclusion
Understanding windows cmd exit codes is invaluable for anyone looking to master the command line or improve their scripting and automation capabilities. By familiarizing yourself with standard exit codes and employing them in your scripts, you increase your productivity and troubleshooting efficiency. Regular practice and exploration of CMD’s capabilities will help solidify this knowledge, making it a crucial part of your skill set.
Windows Cmd Set Env Variable in Just a Few Steps
Further Reading and Resources
For deeper exploration into CMD and batch file programming, consider visiting official documentation, online tutorials, and community forums. These resources can provide ongoing insight and additional support as you continue to learn and implement CMD commands effectively.
The correct name for errorlevels would be return codes.
But since the DOS command to determine the return code is IF ERRORLEVEL
, most people use the name errorlevel.
Errorlevels are not a standard feature of every command.
A certain errorlevel may mean anything the programmer wanted it to.
Most programmers agree that an errorlevel 0 means the command executed successfully, and an errorlevel 1 or higher usually spells trouble.
But there are many exceptions to this general rule.
IF ERRORLEVEL
construction has one strange feature, that can be used to our advantage: it returns TRUE if the return code was equal to or higher than the specified errorlevel.
This means most of the time we only need to check IF ERRORLEVEL 1 ...
and this will return TRUE for every positive, non-zero return code.
Likewise, IF NOT ERRORLEVEL 0 ...
will return TRUE for every negative, non-zero return code.
In CMD.EXE (Windows NT 4 and later) the old-fashioned DOS IF ERRORLEVEL ...
may sometimes fail, since executables may return negative numbers for errorlevels!
However, this can be fixed by using the following code to check for non-zero return codes:
IF %ERRORLEVEL% NEQ 0 ...
Use the code above wherever you would have used IF ERRORLEVEL 1 ...
in the «past».
Thanks for Noe Parenteau for this tip.
In COMMAND.COM (MS-DOS, DOS-box, Windows 9*/ME), to determine the exact return code the previous command returned, we could use a construction like this:
@ECHO OFF IF ERRORLEVEL 1 SET ERRORLEV=1 IF ERRORLEVEL 2 SET ERRORLEV=2 IF ERRORLEVEL 3 SET ERRORLEV=3 IF ERRORLEVEL 4 SET ERRORLEV=4 • • • IF ERRORLEVEL 254 SET ERRORLEV=254 IF ERRORLEVEL 255 SET ERRORLEV=255 ECHO ERRORLEVEL = %ERRORLEV%
This is perfectly OK if we only have to check, say, 15 consecutive errorlevels.
If we need to check every errorlevel, though, there are better alternatives.
(As I learned from Charles Long, in XP the SET command no longer sets an errorlevel itself.)
However, Windows NT 4 and later make it easy by storing the latest errorlevel in the environment variable ERRORLEVEL:
ECHO.%ERRORLEVEL%
will display the errorlevel.
This blog entry by Batcheero explains perfectly why you should never SET the ERRORLEVEL variable.
The safest way to use errorlevels for
all DOS versions is the reverse order check.Start checking the highest errorlevel that can be expected, then check for the one below, etcetera:
IF ERRORLEVEL 255 GOTO Label255
IF ERRORLEVEL 254 GOTO Label254
•
•
•
IF ERRORLEVEL 2 GOTO Label2
IF ERRORLEVEL 1 GOTO Label1
GOTO Label0
:Label255
(commands to be executed at errorlevel 255)
GOTO End
•
•
•
:Label1
(commands to be executed at errorlevel 1)
GOTO End
:Label0
(commands to be executed at errorlevel 0, or no errorlevel)
:End
This will result in many more lines of batch code, but at least it will work in any DOS version.
In Windows NT (Windows NT 4 … Windows 10) this may not suffice, though, because errorlevels can have negative integer values as well.
In DOS (COMMAND.COM), we can use FOR loops to determine the errorlevel:
@ECHO OFF REM Reset variables FOR %%A IN (1 10 100) DO SET ERR%%A= REM Check error level hundredfolds FOR %%A IN (0 1 2) DO IF ERRORLEVEL %%A00 SET ERR100=%%A IF %ERR100%==2 GOTO 200 IF %ERR100%==0 IF NOT "%1"=="/0" SET ERR100= REM Check error level tenfolds FOR %%A IN (0 1 2 3 4 5 6 7 8 9) DO IF ERRORLEVEL %ERR100%%%A0 SET ERR10=%%A IF "%ERR100%"=="" IF %ERR10%==0 SET ERR10= :1 REM Check error level units FOR %%A IN (0 1 2 3 4 5) DO IF ERRORLEVEL %ERR100%%ERR10%%%A SET ERR1=%%A REM Modification necessary for errorlevels 250+ IF NOT ERRORLEVEL 250 FOR %%A IN (6 7 8 9) DO IF ERRORLEVEL %ERR100%%ERR10%%%A SET ERR1=%%A GOTO End :200 REM In case of error levels over 200 both REM tenfolds and units are limited to 5 REM since the highest DOS error level is 255 FOR %%A IN (0 1 2 3 4 5) DO IF ERRORLEVEL 2%%A0 SET ERR10=%%A IF ERR10==5 FOR %%A IN (0 1 2 3 4 5) DO IF ERRORLEVEL 25%%A SET ERR1=%%A IF NOT ERR10==5 GOTO 1 :End REM Clean up the mess and show results SET ERRORLEV=%ERR100%%ERR10%%ERR1% FOR %%A IN (1 10 100) DO SET ERR%%A= ECHO ERRORLEVEL %ERRORLEV%
This example still handles only 255 error levels (that’s all there is in DOS), but it can be easily adjusted once you understand the basic principles.
To check errorlevels during batch file development, use either COMMAND /Z yourbatch.bat to display the errorlevel of every command executed in MS-DOS 7.* (Windows 95/98), or PROMPT Errorlevel$Q$R$_$P$G in OS/2 Warp (DOS) sessions.
Setting errorlevels
MS-DOS & Windows 9x:
Use ERRORLVL.EXE from OzWoz Software, or SETERLEV.COM 1.0 from Jim Elliott to test batch files that (are supposed to) check on errorlevels.
The syntax couldn’t be simpler:
ERRORLVL number
or
SETERLEV number
where number can be any number from 0 to 255.
A small Kix «one liner» can be used too:
EXIT $ErrLev
If called by a batch like this:
KIX32 ERRORLEVEL.KIX $ErrLev=23
it will return an errorlevel 23 (ERRORLEVEL.KIX would be the name of the kix script mentioned above).
Or use CHOICE.COM, available in all DOS 6.* and up versions, to set an errorlevel:
ECHO 5 | CHOICE /C:1234567890 /N
and
ECHO E | CHOICE /C:ABCDEFGHIJ /N
will both result in errorlevel 5 since both 5 and E are the fifth choice (/C:…) in the corresponding CHOICE commands.
Windows NT 4 and later:
In NT 4 use either
COLOR 00
or
VERIFY OTHER 2> NUL
to set an errorlevel 1.
Windows 2000 and later:
In Windows 2000 and later the EXIT
command accepts an optional exit code, a.k.a. return code or errorlevel, e.g. EXIT /B 1
for errorlevel 1:
EXIT
Quits the CMD.EXE program (command interpreter) or the current batch script.
EXIT [ /B ] [ exitCode ]
/B | Specifies to exit the current batch script instead of CMD.EXE. If executed from outside a batch script, it will quit CMD.EXE. |
exitCode | Specifies a numeric number. If /B is specified, sets ERRORLEVEL that number. If quitting CMD.EXE, sets the process exit code with that number. |
[ Brought to my attention by Maor Conforti. Thanks ]
If you want to set an errorlevel inside a batch file, for example to test an external command used by that batch file, you can use CMD.EXE /D /K EXIT 6
to set errorlevel 6 and continue.
CMD
‘s /D
switch disables any command processor AutoRun commands you may have set on your computer (you can check this by looking for HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
in the registry).
Do NOT use SET ErrorLevel=6
as this will render the Errorlevel
variable static (SET ErrorLevel=
will restore it to a dynamic variable again).
[ Addition of /D
to disable AutoRun by Isidro. Thanks ]
Related stuff
• Use EXIT in Windows 2000 (and later) to set errorlevels.
• See how errorlevels are used to check the availability of third party tools, and how your batch file can even help the user download the tool if it isn’t available.
• This blog entry by Batcheero explains perfectly why you should never SET the ERRORLEVEL variable.
The same goes for other dynamic environment variables like CD (current directory), DATE (current date), TIME (current time), RANDOM (random decimal number between 0 and 32767), CMDEXTVERSION (current Command Processor Extensions version) and CMDCMDLINE (the original command line that invoked the Command Processor).
page last modified: 2025-02-10; loaded in 0.0039 seconds