2024年6月30日 星期日

Batch Script - Return Code

 

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

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.

221225495

0xC0000017

-1073741801

Not enough virtual memory is available.

It 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 the 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 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

IF %ERRORLEVEL% NEQ 0 ( 
   DO_Something 
)

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

if not exist c:\lists.txt exit 7 
if not defined userprofile exit 9 
exit 0

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.

Call Find.cmd

if errorlevel gtr 0 exit 
echo Successful completion

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.

 

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 following diagram shows the diagrammatic explanation of this loop.

While Statement Implementation

The first part of the while implementation is to set the counters which will be used to control the evaluation of the ‘if’ condition. We then define our label which will be used to embody the entire code for the while loop implementation. The ‘if’ condition evaluates an expression. If the expression evaluates to true, the code block is executed. If the condition evaluates to false then the loop is exited. When the code block is executed, it will return back to the label statement for execution again.

Following is the syntax of the general implementation of the while statement.

Syntax

Set counters
:label
If (expression) (
   Do_something
   Increment counter
   Go back to :label
)
  • The entire code for the while implementation is placed inside of a label.

  • The counter variables must be set or initialized before the while loop implementation starts.

  • The expression for the while condition is done using the ‘if’ statement. If the expression evaluates to true then the relevant code inside the ‘if’ loop is executed.

  • A counter needs to be properly incremented inside of ‘if’ statement so that the while implementation can terminate at some point in time.

  • Finally, we will go back to our label so that we can evaluate our ‘if’ statement again.

Following is an example of a while loop statement.

Example

@echo off
SET /A "index = 1"
SET /A "count = 5"
:while
if %index% leq %count% (
   echo The value of index is %index%
   SET /A "index = index + 1"
   goto :while
)

In the above example, we are first initializing the value of an index integer variable to 1. Then our condition in the ‘if’ loop is that we are evaluating the condition of the expression to be that index should it be less than the value of the count variable. Till the value of index is less than 5, we will print the value of index and then increment the value of index.

Output

The above command produces the following output.

The value of index is 1
The value of index is 2
The value of index is 3
The value of index is 4
The value of index is 5

For Statement List Implementations

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.

Syntax

FOR %%variable IN list DO do_something

The classic ‘for’ statement consists of the following parts −

  • Variable declaration – This step is executed only once for the entire loop and used to declare any variables which will be used within the loop. In Batch Script, the variable declaration is done with the %% at the beginning of the variable name.

  • List – This will be the list of values for which the ‘for’ statement should be executed.

  • The do_something code block is what needs to be executed for each iteration for the list of values.

The following diagram shows the diagrammatic explanation of this loop.

For Statement - List Implementations

Following is an example of how the ‘goto’ statement can be used.

Example

@echo off 
FOR %%F IN (1 2 3 4 5) DO echo %%F

The key thing to note about the above program is −

  • The variable declaration is done with the %% sign at the beginning of the variable name.

  • The list of values is defined after the IN clause.

  • The do_something code is defined after the echo command. Thus for each value in the list, the echo command will be executed.

Output

The above program produces the following output.

1 
2 
3 
4 
5 
 

Looping through Ranges

The ‘for’ statement also has the ability to move through a range of values. Following is the general form of the statement.

Syntax

FOR /L %%variable IN (lowerlimit,Increment,Upperlimit) DO do_something

Where

  • The /L switch is used to denote that the loop is used for iterating through ranges.

  • Variable declaration – This step is executed only once for the entire loop and used to declare any variables which will be used within the loop. In Batch Script, the variable declaration is done with the %% at the beginning of the variable name.

  • The IN list contains of 3 values. The lowerlimit, the increment, and the upperlimit. So, the loop would start with the lowerlimit and move to the upperlimit value, iterating each time by the Increment value.

  • The do_something code block is what needs to be executed for each iteration.

Following is an example of how the looping through ranges can be carried out.

Example

@ECHO OFF 
FOR /L %%X IN (0,1,5) DO ECHO %%X

Output

The above program produces the following output.

0 
1 
2 
3 
4 
5 
 
 
 

 

Classic for Loop Implementation

Following is the classic ‘for’ statement which is available in most programming languages.

Syntax

for(variable declaration;expression;Increment) {
   statement #1
   statement #2
   …
}

The Batch Script language does not have a direct ‘for’ statement which is similar to the above syntax, but one can still do an implementation of the classic ‘for’ loop statement using if statements and labels.

Following is the general flow of the classic ‘for’ loop statement.

Classic for Loop Implementation

Let’s look at the general syntax implementation of the classic for loop in batch scripting.

Set counter
:label

If (expression) exit loop
Do_something
Increment counter
Go back to :label
  • The entire code for the ‘for’ implementation is placed inside of a label.

  • The counters variables must be set or initialized before the ‘for’ loop implementation starts.

  • The expression for the ‘for’ loop is done using the ‘if’ statement. If the expression evaluates to be true then an exit is executed to come out of the loop.

  • A counter needs to be properly incremented inside of the ‘if’ statement so that the ‘for’ implementation can continue if the expression evaluation is false.

  • Finally, we will go back to our label so that we can evaluate our ‘if’ statement again.

Following is an example of how to carry out the implementation of the classic ‘for’ loop statement.

Example

@echo off 
SET /A i = 1 
:loop 

IF %i%==5 GOTO END 
echo The value of i is %i% 
SET /a i=%i%+1 
GOTO :LOOP 
:END

Output

The above command produces the following output.

The value of i is 1 
The value of i is 2 
The value of i is 3 
The value of i is 4

 

 

 

 

 

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

@ECHO OFF 
:Loop 

IF "%1"=="" GOTO completed 
FOR %%F IN (%1) DO echo %%F 
SHIFT 
GOTO Loop 
:completed

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.

1 
2 
3

 

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.

The Batch Script language does not have a direct ‘for’ statement which does a break but this can be implemented by using labels. The following diagram shows the diagrammatic explanation of the break statement implementation in Batch Script.

Break Statement Implementation

The key thing to note about the above implementation is the involvement of two ‘if’ conditions. The second ‘if’ condition is used to control when the break is implemented. If the second ‘if’ condition is evaluated to be true, then the code block is not executed and the counter is directly implemented.

Following is an example of how to carry out the implementation of the break statement.

Example

@echo off 
SET /A "index=1" 
SET /A "count=5" 
:while 
if %index% leq %count% ( 
   if %index%==2 goto :Increment 
      echo The value of index is %index% 
:Increment 
   SET /A "index=index + 1" 
   goto :while 
)

The key thing to note about the above program is the addition of a label called :Increment. When the value of index reaches 2, we want to skip the statement which echoes its value to the command prompt and directly just increment the value of index.

Output

The above command produces the following output.

The value of index is 1 
The value of index is 3 
The value of index is 4 
The value of index is 5

 

 

 

 

沒有留言: