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. For this task, you use the Call command described in the "Using the Call Command" section of the tutorial. 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-1 and 2 both show the Goto command in action.
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. For an example of a command that exits with special conditions, review the Choice command in the "Using the Choice Command" section of the tutorial. Error conditions can represent a user, system, or application failure. For example, consider the XCopy error levels shown in Table-5.
Table-5: XCopy Error LevelsError 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.
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 Echo command 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.
So far, the tutorial has discussed the standard form of the If command that you can execute even at the DOS prompt. 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, theentire 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 Number Tests 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 Variable Tests 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.
Using the Pause Command
The Pause command stops batch file execution to give the user time to react to a particular need. For example, if you need the user to change media to complete the batch file, you could use the Echo command to tell the user about the need and then use the Pause command to tell the user to press any key when the media exchange is complete.
In this tutorial:
- CMD and BAT Files
- Starting the Command Interpreter
- Using the CMD Switches
- Working with the Command Interpreter in the Registry
- Modifying Config.NT
- Displaying the Config.NT Commands
- Modifying AutoExec.NT
- Saving Memory Using the LH Command
- Defining Application Compatibility with the SetVer Utility
- Using Common DOS Utilities
- Formatting a Disk with the Format Utility
- Terminating a Session Using the Logoff Utility
- Managing Environment Variables with the Set Command
- Managing Environment Variables with the SetX Utility
- Using Debugging Utilities
- Working at the Command Prompt
- Managing Usernames and Passwords with CmdKey
- Changing Screen Colors with the Color Command
- Obtaining Command Line Help with the Help Utility
- Creating Batch Files
- Using the Choice Command
- Using the For Command
- Using the Goto Command
- Using the Prompt Command
- Using the WaitFor Utility