Command line check error code



/* 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.

Читайте также:  Supervisorctl start error no such process

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.

Not enough virtual memory is available.

It indicates that Windows has run out of memory.

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 Arguments

The ‘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.

Example

Output

Let’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.

S.No Loops & Description
1 Break Statement Implementation

The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop.

Источник

Exit Codes

These can be used within a shell script to change the flow of execution depending on the success or failure of commands executed. This was briefly introduced in Variables — Part II. Here we shall look in more detail in the available interpretations of exit codes.

Success is traditionally represented with exit 0 ; failure is normally indicated with a non-zero exit-code. This value can indicate different reasons for failure.
For example, GNU grep returns 0 on success, 1 if no matches were found, and 2 for other errors (syntax errors, non-existent input files, etc).

We shall look at three different methods for checking error status, and discuss the pros and cons of each approach.

Firstly, the simple approach: This script works fine if you supply a valid username in /etc/passwd . However, if you enter an invalid code, it does not do what you might at first expect — it keeps running, and just shows:Why is this? As mentioned, the $? variable is set to the return code of the last executed command. In this case, that is cut . cut had no problems which it feels like reporting — as far as I can tell from testing it, and reading the documentation, cut returns zero whatever happens! It was fed an empty string, and did its job — returned the first field of its input, which just happened to be the empty string.

So what do we do? If we have an error here, grep will report it, not cut . Therefore, we have to test grep ‘s return code, not cut ‘s.

This fixes the problem for us, though at the expense of slightly longer code.
That is the basic way which textbooks might show you, but it is far from being all there is to know about error-checking in shell scripts. This method may not be the most suitable to your particular command-sequence, or may be unmaintainable. Below, we shall investigate two alternative approaches.

As a second approach, we can tidy this somewhat by putting the test into a separate function, instead of littering the code with lots of 4-line tests: This allows us to test for errors 3 times, with customised error messages, without having to write 3 individual tests. By writing the test routine once. we can call it as many times as we wish, creating a more intelligent script, at very little expense to the programmer. Perl programmers will recognise this as being similar to the die command in Perl.

As a third approach, we shall look at a simpler and cruder method. I tend to use this for building Linux kernels — simple automations which, if they go well, should just get on with it, but when things go wrong, tend to require the operator to do something intelligent (ie, that which a script cannot do!): This script runs through the various tasks involved in building a Linux kernel (which can take quite a while), and uses the && operator to check for success. To do this with if would involve: . which I, personally, find pretty difficult to follow.

The && and || operators are the shell’s equivalent of AND and OR tests. These can be thrown together as above, or:

This code will either echo

depending on whether or not the cp command was successful. Look carefully at this; the construct is

Only one command can be in each part. This method is handy for simple success / fail scenarios, but if you want to check on the status of the echo commands themselves, it is easy to quickly become confused about which && and || applies to which command. It is also very difficult to maintain. Therefore this construct is only recommended for simple sequencing of commands.

In earlier versions, I had suggested that you can use a subshell to execute multiple commands depending on whether the cp command succeeded or failed:

But in fact, Marcel found that this does not work properly. The syntax for a subshell is:

The return code of the subshell is the return code of the final command ( command3 in this example). That return code will affect the overall command. So the output of this script:

Is that it runs the Success part (because cp succeeded, and then — because /bin/false returns failure, it also executes the Failure part:

So if you need to execute multiple commands as a result of the status of some other condition, it is better (and much clearer) to use the standard if , then , else syntax.

Books and eBooks

My Shell Scripting books, available in Paperback and eBook formats.

Buy this tutorial as a PDF for only $5!

Shell Scripting Tutorial is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and to keep by your desk as an ever-present companion. Shell Scripting: Expert Recipes for Linux, Bash and more is my 564-page book on Shell Scripting. The first half explains the features of the shell; the second half has real-world shell scripts, organised by topic, with detailed discussion of each script.

Contact

You can mail me with this form. If you expect a reply, please ensure that the address you specify is valid. Don’t forget to include the simple addition question at the end of the form, to prove that you are a real person!

You can buy the content of this Shell Scripting Tutorial as a PDF!

Источник

Оцените статью
toolgir.ru
Adblock
detector