Cmd errorlevel exit

cmd errorlevel exit

Program exit codes allow determining the specific reason for command's or application's termination. Although Automation Workshop shows codes in decimal. You can use the SetExitC utility and the ERRORLEVEL variable to send the exit code from a Windows batch file to ESP. 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. cmd errorlevel exit

Cmd errorlevel exit - share your


In this tutorial, you will learn about batch file return code, what is a return code and how is it used in batch file programming.

return code batch file

Batch file return code – Introduction


So, a return code is a code returned after the execution of a program. By default, the command line execution should return zero when execution succeeds and non-zero when execution fails. When execution fails, the returned non-zero value indicates the corresponding error number and user can go through that error to resolve it.

These returned error codes are also called exit codes. Almost all application or utilities return the exit code when they are complete or they terminate.

Following are some of the non-zero numbers (exit codes) returned from programs with their corresponding errors.

Exit Code/Error CodeDetails/Description
0Program successfully executed.
1Incorrect function. Indicates that Action has attempted to execute non-recognized command in Windows command prompt cmd.exe.
2Indicates that the system cannot find the file in that specified location.
3Indicates that the system cannot find the specified path.
5Access is denied. So the user has no access right to specified resource.
9009
0x2331
Program is not recognized as an internal or external command, operable program or batch file. Indicates that command, application name or path has been misspelled when configuring the Action.
3221225477
0xC0000005
-1073741819
Access violation.
Indicates that the executed program has terminated abnormally or crashed.
3221225495
0xC0000017
-1073741801
Not enough virtual memory is available.
Indicates that Windows has run out of memory.
3221225786
0xC000013A
-1073741510
The application terminated as a result of a CTRL+C. Indicates that the application has been terminated either by user’s keyboard input CTRL+C or CTRL+Break or closing command prompt window.
3221225794
0xC0000142
-1073741502
The application failed to initialize properly. Indicates that the application has been launched on a Desktop to which current user has no access rights. Another possible cause is that either gdi32.dll or user32.dll has failed to initialize.
221225495
0xC0000017
-1073741801
Not enough virtual memory is available.

It indicates that Windows has run out of memory.

3221226505
0xC0000409
-1073740791
Stack buffer overflow / overrun. Error can indicate a bug in the executed software that causes stack overflow, leading to abnormal termination of the software.
3762507597
0xE0434F4D
-532459699
Unhandled exception in .NET application. More details may be available in Windows Event log.

Now that we know about exit codes, the next thing is to know or check the return codes in our script commands. For that, environment variable is used.

Error Level In Batch File


The environmental variable contains the return code or the latest error level in the batch file, which is the latest error codes from the last command executed.

A common way of checking Error levels using variable is:

Besides this, the command at the end of the batch file also returns the error codes from the batch file.

is used to return custom return codes.

Batch file return code example


Here is a simple example to illustrate how to check error codes in a batch file.

So, basically what this script does is, it checks D: for file abc.txt. If the file exist, it will return error code zero and terminate and if the file abc.txt doesn’t exist in D: , then it will return error code 9 and terminate.



EXIT

Close the current batch script, exit the current subroutine or close the CMD.EXE session, optionally setting an errorlevel.

Syntax EXIT [/B] [exitCode] Key /B When used in a batch script, this option will exit only the script (or subroutine) but not CMD.EXE If executed on the command-line it will close CMD.exe exitCode Sets the %ERRORLEVEL% to a numeric number. If quitting CMD.EXE, sets the process exit code no.

To close an interactive command prompt, the keyboard shortcut ALT + F4 is an alternative to typing EXIT.

If you start a second nested CMD shell (or PowerShell), this will be added to the TITLE of the CMD/terminal window, when you EXIT back to the initial shell, the Title will also revert making it possible to track how many nested shells you have open.

Errorlevel

EXIT /b has the option to set a specific exit code, EXIT /b 0 for sucess, EXIT /b 1 (or greater) for an error.
The exit code can be an integer of up to 10 digits in length (positive or negative).

EXIT without an ExitCode acts the same as goto:eof and will not alter the ERRORLEVEL

n.b. You should never attempt to directly write to the %ERRORLEVEL% variable, (SET ERRORLEVEL n ) instead use EXIT /b n as a safe way to set the internal ERRORLEVEL pseudo variable to n.

Ctrl-C

An errorlevel of -1073741510 will be interpreted by CMD.exe as a Ctrl-C Key sequence to cancel the current operation, not the entire script which EXIT will do.

To use this in a batch file, launch a new CMD session and immediately exit it, passing this errorlevel. The script will then act as though Ctrl-C had been pressed. Source and examples on DosTips.com.

::Ctrl-C
cmd /c exit -1073741510

When EXIT /b used with FOR /L, the execution of the commands in the loop is stopped, but the loop itself continues until the end count is reached. This will cause slow performance if the loop is (pointlessly) counting up to a large number.
In the case of an infinite loop, this EXIT /b behaviour will cause the script to hang until manually terminated with Ctrl + C

Exiting nested FOR loops, EXIT /b can be used to exit a FOR loop that is nested within another FOR loop.
This will only work if the inner FOR loop is contained in a separate subroutine, so that EXIT /b (or goto:eof) will terminate the subroutine.

Examples

Exit if a required file is missing:

@Echo Off
If not exist MyimportantFile.txt Exit /b
Echo If we get this far the file was found

Set the errorlevel to 5:

@Echo Off
Call :setError
Echo %errorlevel%
Goto :eof

:setError
Exit /B 5

Use EXIT /b to exit a nested FOR loop (so skipping the values X,Y and Z), but still continue back to the main outer loop:

@Echo Off Setlocal For %%A in (alpha beta gamma) DO ( Echo Outer loop %%A Call :inner ) Goto :eof :inner For %%B in (U V W X Y Z) DO ( if %%B==X ( exit /b 2 ) Echo Inner loop Outer=%%A Inner=%%B )

EXIT is an internal command.
If Command Extensions are disabled, the EXIT command will still work but may output a spurious 'cannot find the batch label' error.

“Making music is not about a place you go. It’s about a place you get out of. I’m underwater most of the time, and music is like a tube to the surface that I can breathe through. It’s my air hole up to the world. If I didn’t have the music I’d be under water, dead” ~ Fiona Apple

Related commands:

VERIFY - Provides an alternative method of raising an error level without exiting.
TSKILL - End a running process.
Equivalent PowerShell: Exit - Exit PowerShell or break - Exit a program loop.
Equivalent bash command (Linux):break - Exit from a loop.


 

Copyright © 1999-2022 SS64.com
Some rights reserved

Echo An error was found

This allows you to trap errors that can be negative numbers, you can also test for specific errors:
IF %ERRORLEVEL% EQU 64 ...

When ending a subroutine, you can use EXIT /b N to set a specific ERRORLEVEL N.

Raymond Chen [MSFT] explains: ERRORLEVEL is not the same as the %ERRORLEVEL% environment variable.

Error Message/Error Stream

In addition to setting an ERRORLEVEL, many utilities will output an error message on the error stream (STDERR), by default these messages will appear on the console, but they can be redirected with 2>.

Many utilities set an ERRORLEVEL and also output some error text, some utilities set an ERRORLEVEL but don’t display error text and some will display error text without setting an ERRORLEVEL. Some utilities behave differently depending on the severity of the error.

Error messages are likely to be different for each language/locale so it is generally more robust to just test the ERRORLEVEL rather than any text message output.

Error level vs Exit code

When an external command is run by CMD.EXE, it will detect the executable's Return or Exit Code and set the ERRORLEVEL to match. In most cases the ERRORLEVEL will be the same as the Exit code, but there are some cases where they can differ.

An Exit Code can be detected directly with redirection operators (Success/Failure ignoring the ERRORLEVEL) this can often be more reliable than trusting the ERRORLEVEL which may or may not have been set correctly.

Old style .bat Batch files vs .cmd Batch scripts.

Although the differences are minor, there are no advantages to the .BAT extension, so I recommend using .CMD exclusively.

There is a key difference between the way .CMD and .BAT batch files set errorlevels:

A .CMD batch script will set/reset the ERRORLEVEL after every command that you run [source] Mark Zbikowski (MSFT).

A .BAT batch script running the internal commands: APPEND, ASSOC, PATH, PROMPT, FTYPE and SET will only change the ERRORLEVEL if an error occurs. Other internal and external commands do not follow this rule.

So if you have two commands in a .BAT script and the first command fails but the second succeeds, the ERRORLEVEL may or may not remain set depending on which command was run.

This lack of consistency in the ERRORLEVELs raised makes debugging a .BAT script more difficult than an equlvalent .CMD script.

Even in the CMD shell, some commands don’t follow the rules

Even though a CMD batch script should set or reset ERRORLEVEL after every command, there are a few exceptions:

Commands that do NOT affect the ERRORLEVEL:
BREAK, ECHO, ENDLOCAL, FOR, IF, PAUSE, REM, RD/RMDIR, TITLE

Commands that will set but not clear an ERRORLEVEL:
CLS, GOTO, KEYS, POPD, SHIFT

Commands that set an Exit Code but not the ERRORLEVEL:
RD/RMDIR

Commands that set an ERRORLEVEL but not the Exit Code (SO explanation):
MD/MKDIR

Set or Force an exit code

You can make a batch file return a non-zero exit code by using the EXIT command.

Exit 0
Exit /B 5

To force an ERRORLEVEL of 1 to be set without exiting, run a small but invalid command like COLOR 00 or run (CALL) which does nothing other than set the ERRORLEVEL to 1.

To clear the ERRORLEVEL back to 0, run (call ), which does nothing except set the ERRORLEVEL to 0.

You should never attempt to SET the %ERRORLEVEL% because that will create a user variable named %ERRORLEVEL% which then takes precedence over the internal pseudo variable %ERRORLEVEL%.
You can clear any such user variable with the following two commands at the start of your script, but really the best practice is to never set a variable with that name in the first place:
Set "errorlevel=1"
Set "errorlevel="

PowerShell

In PowerShell $? contains True if last operation succeeded and False otherwise.

The exit code of the last Win32 executable execution is stored in the automatic variable $LASTEXITCODE

To read exit codes (other than 0 or 1) launch the PowerShell script and return the $LASTEXITCODE in a single line like this:

powershell.exe -noprofile C:\scripts\script.ps1; exit $LASTEXITCODE

“I’d rather wake up in the middle of nowhere than in any city on earth” ~ Steve McQueen

Related commands:

Robocopy exit codes
Conditional Execution - if succeeds then execute
HowTo: Error Handling in a batch file
List of ERRORLEVEL values set by internal cmd.exe commands - Stackoverflow /Aacini.
ERRORLEVEL is not %ERRORLEVEL% - The old new thing blog.


 

Copyright © 1999-2022 SS64.com
Some rights reserved