7. Using the Goto Command
The Goto command transfers control from one part of a batch file to another. You can't use the Goto command to transfer control to other batch files. The Goto command takes a simple form: Goto Label, where Label is a keyword used to define the transfer point in the batch file. Labels are always preceded by a colon, such as :MyLabel. Listings 5.1 and 5.2 both show the Goto command in action.
8. Using the If Command
To write any reasonably
complex batch file, you need to perform flow control—the active
selection of code to run based on current conditions. For example, you
might want to know that the previous task succeeded before you begin the
next task. In some cases, you'll look for a specific file or act on
user input to the batch file. You can also verify that the user provided
a certain input string. The point is that you can exercise some control
over how the batch files react to system and environmental conditions.
Batch files don't provide extensive decision-making support, but you can
use these three forms of the If statement to increase the flexibility of your batch files.
If [Not] ErrorLevel number command
If [Not] string1==string2 command
If [Not] Exist filename command
In all three cases, you
can add the word "Not" to perform the reverse of the check. For example,
you can perform a task when a given file doesn't exist, rather than
when it does exist. By combining both versions of the If statement, you can create the equivalent of an If...Else statement found in most programming languages.
The ErrorLevel
argument requires special consideration. Whenever you run an
application, batch file, or script, the system provides a numeric error
level as output. By convention, an error level of 0 always represents
success. Other numbers represent an error or special condition. A
special condition isn't always an error; it's simply not complete
success. In fact, you might expect an application, batch file, or script
to exit with a special condition. Error conditions can represent a user, system,
or application failure. For example, consider the XCopy error levels
shown in Table 1.
Table 1. XCopy Error Levels
Error Level | Meaning |
---|
0 | Success, no error occurred. |
1 | The system didn't find any files to copy. |
2 | The user stopped XCopy by pressing Ctrl+C. |
4 | The
application experienced an initialization error. The system doesn't
have enough memory or disk space. You may have entered an invalid drive
name or used invalid syntax at the command line. |
5 | The system experienced a disk write error. |
As you can see, the
cause of an error varies greatly depending on conditions. In all cases,
you could rightfully say that the application has experienced an error.
However, notice that error level 2 could actually occur by design. The
user recognizes an error and presses Ctrl+C to stop the copying process
before it completes. In this case, you have to consider whether the
error level defines a special condition or an error by prompting the
user and handle it appropriately. Listing 2 shows examples of the various If statement forms at work.
Example 2. Using the If Statement in Batch Files
Echo Off
REM Verify the user has provided an action.
If %1Err==Err GoTo ProcessError
REM Simulate an error when the file doesn't exist.
Copy MyFile.TXT MyFile2.TXT
If Not ErrorLevel 1 Goto CheckFile
Echo The File doesn't exist so the batch file can't copy it. REM Check for a specific file and process it when it does exist.
:CheckFile
If Exist MyFile.TXT Goto ProcessFile
REM If the file doesn't exist then create it. Display a message with
REM instructions and then let the user type the text.
Echo Type some text for the test file. Press Ctrl+Z when you finish.
Pause
Copy CON MyFile.TXT
REM This is a label for processing the file.
:ProcessFile
REM Determine whether the user wants to display the file.
If Not %1==display Goto Process2
Echo MyFile.TXT Contains:
Type MyFile.TXT
Goto TheEnd
REM Determine whether the user wants to delete the file.
:Process2
If Not %1==delete Goto ProcessError
Erase MyFile.TXT
Echo Deleted MyFile.TXT
Goto TheEnd
REM The user didn't define a processing action.
:ProcessError
Echo You didn't tell the batch file what to do!
Echo Type UseIf Display to display the file or
Echo UseIf Delete to delete the file.
:TheEnd
Echo On
|
The first line of this
example demonstrates a principle that you should always use in batch
files that you expect someone else will use—check for errors within the
limits of the batch file to do so. In this case, the batch file expects
the user to provide an input value of delete or display. When the user doesn't provide any input value, then the first input value, %1, is blank so the string Err equals Err and the code goes to a label named ProcessError. Batch files can work with up to nine input values at a time using %1 through %9 as variables. The Goto
statement always tells the code to go to a label within the batch file.
You define a label by preceding the label name with a colon such as :ProcessError.
The next segment of code
attempts to copy a temporary file to another file. The operation results
in an error that you can trap using the ErrorLevel statement when the file doesn't exist. When the ErrorLevel value matches the value you provide, then the If statement executes the command. In this case, because the code uses the Not clause, the reverse is true, the If statement only executes the Goto command when the error level is not 1. Notice that, in this case, the code uses the Echocommand to display an error message to the user—Echo works not only for turning messages on or off, but for displaying custom messages to the user that the Echo setting doesn't hide as well.
Once the code performs these initial steps, it determines whether the MyFile.TXT file does exist using the Exit clause of the If
statement. When the file exists, the code immediately begins processing
it. Otherwise, the code displays a message prompting the user to type
information for such a file. Notice the Pause command, which pauses the batch file execution until the user presses a key. The Copy command sends whatever the user types at the console (CON) to the MyFile.TXT file until it detects an end of file character, which the user creates by pressing Ctrl+Z.
Now that you know the
file exists, the batch file can process it. This batch file provides two
options: displaying the file and deleting it. The problem with batch
files is that they use case-sensitive string comparisons—the word delete is different from the word Delete
so error trapping can cause false problems. Some developers resolve
this problem by using single character command line switches for batch
files. That way, all you need to do is perform two checks, one for
uppercase and another for lowercase. The example uses a full word for
the purpose of demonstration. To see how this works, type Delete at the command line instead of delete—the code displays a failure message. When the user does type delete, the batch file erases the file and displays a success message. Likewise, when the user types display, the code sends the content of MyFile.TXT to the display. In both cases, the code goes to TheEnd where the batch file turns Echo back on.
The If command has the following additional syntax forms when you use command line extensions.
if [/i] String1 CompareOp String2 Command [else Expression]
if CMDEXTVERSION Number Command [else Expression]
if DEFINED Variable Command [else Expression]
The following list describes each of the command line arguments.
- /I
Performs a
case-insensitive comparison of the two strings. This feature is handy
when you expect the user to input a string, but don't know how the user
will capitalize it. These comparisons are generic, in that if both String1 and String2 are composed of numbers, the system converts the strings to numbers and performs a numeric comparison.
- String1
Specifies the input string; the first half of the comparison.
- CompareOp
Defines the
comparison operator. Each three-letter comparison operator performs a
different comparison as described in the following list.
EQU Equal to
NEQ Not equal to
LSS Less than
LEQ Less than or equal to
GTR Greater than
GEQ Greater than or equal to
- String2
Specifies the comparison string—the second half of the comparison.
- Command
Specifies the command that you want to execute when the comparison is true.
- else
- Expression
Defines the else expression for the If command. When you use this syntax, you must surround the If and Else
portions of the statement in parentheses. In addition, the entire
statement must appear on a single line. You can't separate the various
elements to provide a neater appearance. Here's an example of this form
of the If command.
IF [%1] EQU [] (ECHO String Empty) ELSE (ECHO String Has Data)
In this case, the If
command checks whether the input has a string for the first variable.
When the input is available, the output tells the user that the string
has data. Otherwise, the input displays, "String Empty" as output.
CMDEXTVERSION
NumberTests for a
specific version of the command extensions feature. When the command
extension version number is equal to or greater than the specified
number, the condition is true. This form of If command never returns true when you disable command extensions.
DEFINED
VariableTests whether you have a specific environment variable defined. The DEFINED argument works just like the EXISTS argument. The If command returns true when the variable is defined.