Windows cmd exit codes

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

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

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

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

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

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

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.

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!

How to Get the Application Exit Code from a Windows Command Line 💻🔚

So you’re running a program on your Windows command line, and you want to know its exit code, huh? 🤔 No worries, we’ve got you covered! In this guide, we’ll show you how to retrieve the application exit code from your Windows command line and understand what it means. 💡

Understanding the Exit Code 🆘

Before diving into the solutions, let’s first understand what an exit code is. When a program finishes executing, it usually returns a code, called an «exit code,» which indicates its current state. These exit codes help you determine if the program executed successfully or encountered any errors or issues along the way. 🚦

Exit codes are numeric values that can range from 0 to 255. While 0 usually represents a successful execution, non-zero values generally denote different types of errors or warnings. Each program can define its own set of exit codes, so make sure to refer to the program’s documentation for specific meanings. 📑

Solution: Using the ERRORLEVEL Variable 🛠️💯

When using cmd.exe on Windows, you can access the exit code of the previously executed program through the ERRORLEVEL environment variable. Simply follow these steps:

  1. Run the program you want to retrieve the exit code from. 🏃

  2. Afterward, open your Windows command line and type the following command:

echo %ERRORLEVEL%
  1. Press Enter, and voila! 💥 The command prompt will display the exit code of the last program you executed.

Example Scenario 🌟📋

To give you a better idea, let’s go through an example. Say we have a program called «my_program.exe» that validates user input. This program returns an exit code of 1 if the input is invalid and 0 if it’s valid.

  1. Run the program by executing the following command:

my_program.exe
  1. Once it finishes executing, open your command line and type:

echo %ERRORLEVEL%
  1. If the command prompt displays 1, it means the input was invalid. If you see 0, then hooray! 🎉 The input was valid.

Your Mission: Decode the Exit Code! 🔍

Now that you understand how to retrieve the exit code, it’s time for some real-world problem-solving! 🕵️🔎

Whenever you encounter a program that returns an exit code, use the steps above to decipher what it means. 🤓 You can refer to the program’s documentation or conduct online research to understand the significance of the exit code you receive. By doing so, you’ll quickly identify any errors or warnings and take appropriate action. 💪

Share Your Success! 📣🎉

Now that you’ve mastered the art of retrieving the application exit code from a Windows command line, it’s time to celebrate your newfound knowledge! 🎉

Share this post with your friends, colleagues, or anyone baffled by those mysterious exit codes. Let’s demystify the command line and empower more people to become coding commandos! 💪🔥

Leave a comment and let us know about your experiences with exit codes. Have you ever encountered an unusual exit code? How did you troubleshoot it? We’d love to hear your stories and insights! 📝💬

Remember, exit codes are your secret weapons for taming the command line jungle. Embrace them, understand them, and conquer them! Happy coding! 👨‍💻💥

Disclaimer: The exit codes mentioned in this post are for illustration purposes only. Make sure to refer to the specific program’s documentation to interpret the correct meanings of its exit codes.


I hope this guide helped you grasp the process of retrieving the application exit code from a Windows command line! Feel free to reach out if you have any more questions. Remember, the command line is your playground — conquer it! 💪🌟

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.
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:

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:

Output

Rob van der Woude's Scripting Pages

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.

In Windows NT 4 (and 2000?) this won’t work, since the SET command itself will set an errorlevel (usually 0)!
(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.0014 seconds

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как ввести комп в домен windows 10
  • Как отключить активацию windows 7 максимальная
  • Как включить диспетчер задач на windows 10 через реестр
  • Как восстановить брандмауэр windows 10 по умолчанию
  • Point blank на windows 10