/* steve jansen */
// another day in paradise hacking code and more
Windows Batch Scripting: Return Codes
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:
Another common technique is:
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.
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:
To execute a follow-on command after failure, we use the || operator:
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.
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.
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:
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.
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.
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.
Posted by Steve Jansen Mar 1 st , 2013 batch, scripting, shell, windows
Comments
Hi, I’m Steve. I’m a software developer loving life in Charlotte, NC, an (ISC) 2 CSSLP and an avid fan of Crossfit.
And, no, I’m not Steve Jansen the British jazz drummer, though that does sound like a sweet career.
Guides
Recent Posts
Social Stuff
- @steve-jansen on GitHub
- @steve-jansen on StackOverflow
- @steve-jansen ProTips on Coderwall
- @steve-jansen on Microsft Connect
- @steve-jansen on ASP.NET User Voice
- Subscribe via RSS
Copyright © 2015 — Steve Jansen — Powered by Octopress
Batch Script — Return Code
Complete Python Prime Pack for 2023
9 Courses 2 eBooks
Artificial Intelligence & Machine Learning Prime Pack
6 Courses 1 eBooks
Java Prime Pack 2023
8 Courses 2 eBooks
By default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number. We will then use the error number to determine what the error is about and resolve it accordingly.
Following are the common exit code and their description.
Error Code | Description |
---|---|
Program successfully completed. | |
1 | Incorrect function. Indicates that Action has attempted to execute non-recognized command in Windows command prompt cmd.exe. |
2 | The system cannot find the file specified. Indicates that the file cannot be found in specified location. |
3 | The system cannot find the path specified. Indicates that the specified path cannot be found. |
5 | Access is denied. Indicates that user has no access right to specified resource. |
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. | |
The application terminated as a result of a CTRL+C. Indicates that the application has been terminated either by the user’s keyboard input CTRL+C or CTRL+Break or closing command prompt window. | |
The application failed to initialize properly. Indicates that the application has been launched on a Desktop to which the current user has no access rights. Another possible cause is that either gdi32.dll or user32.dll has failed to initialize. |
Error Level
The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script.
By default, the way to check for the ERRORLEVEL is via the following code.
Syntax
It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file.
EXIT /B at the end of the batch file will stop execution of a batch file.
Use EXIT /B at the end of the batch file to return custom return codes.
Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed. In the batch file, it is always a good practice to use environment variables instead of constant values, since the same variable get expanded to different values on different computers.
Let’s look at a quick example on how to check for error codes from a batch file.
Example
Let’s assume we have a batch file called Find.cmd which has the following code. In the code, we have clearly mentioned that we if don’t find the file called lists.txt then we should set the errorlevel to 7. Similarly, if we see that the variable userprofile is not defined then we should set the errorlevel code to 9.
Let’s assume we have another file called App.cmd that calls Find.cmd first. Now, if the Find.cmd returns an error wherein it sets the errorlevel to greater than 0 then it would exit the program. In the following batch file, after calling the Find.cnd find, it actually checks to see if the errorlevel is greater than 0.
Output
In the above program, we can have the following scenarios as the output −
If the file c:\lists.txt does not exist, then nothing will be displayed in the console output.
If the variable userprofile does not exist, then nothing will be displayed in the console output.
If both of the above condition passes then the string “Successful completion” will be displayed in the command prompt.
Loops
In the decision making chapter, we have seen statements which have been executed one after the other in a sequential manner. Additionally, implementations can also be done in Batch Script to alter the flow of control in a program’s logic. They are then classified into flow of control statements.
S.No | Loops & Description | ||||||
---|---|---|---|---|---|---|---|
1 | While Statement Implementation There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels. The «FOR» construct offers looping capabilities for batch files. Following is the common construct of the ‘for’ statement for working with a list of values. The ‘for’ statement also has the ability to move through a range of values. Following is the general form of the statement. Following is the classic ‘for’ statement which is available in most programming languages. Looping through Command Line ArgumentsThe ‘for’ statement can also be used for checking command line arguments. The following example shows how the ‘for’ statement can be used to loop through the command line arguments. ExampleOutputLet’s assume that our above code is stored in a file called Test.bat. The above command will produce the following output if the batch file passes the command line arguments of 1,2 and 3 as Test.bat 1 2 3.
|