Chapter 16. Understanding Batch Files

Introducing Batch Files

When you discover that you're repeatedly performing a certain task on your computer, you should look for a way to get the computer to do more of the work. Your computer can perform most tasks faster than you can, and it doesn't make mistakes.

DOS has always enabled you to automate your use of DOS commands by creating batch files. A batch file is a text (ASCII) file containing a series of commands that you want DOS to execute. When you type the batch filename, DOS executes these commands in the order they occur within the batch file.

The idea of getting a computer to perform work in convenient, manageable batches predates the personal computer by several years. The earliest computers were large and expensive, and they could do only one job at a time. But even these early machines were fast. Making them wait for keyboard input between jobs was inefficient.

Batch processing was developed to make computers more productive. Collections of tasks to be carried out consecutively were put together offline—that is, without using the computer's resources. The chunks, or batches, of tasks then were fed to the computer at a rate that kept the computer busy and productive.

Today, computers are less expensive than human resources. Batch processing enables computers to carry out a series of tasks automatically so that people don't have to waste time typing frequently used or complex commands.

A batch file is a text file that contains a series of DOS commands. Most commands used in batch files are familiar to you, having been explained in previous chapters of this book. Other commands, which control the flow of action during batch processing are available for use only in batch files. DOS executes the commands in a batch file one line at a time, treating each command as though you issued it individually.

You can use batch files to automate a DOS process. Using a set of commands in a batch file, you actually create a new, more powerful command. After a few experiments, you will find this DOS feature quite handy.

Recognizing a batch file in a directory listing is easy; batch files always have the filename extension BAT. You can execute a batch file by typing the filename at the DOS prompt and then pressing Enter. To execute the batch file SAFE.BAT, for example, you type the following at the DOS prompt and press Enter:

SAFE

COMMAND.COM looks in the current directory for a file named SAFE.COM, then SAFE.EXE, and finally SAFE.BAT. After finding the file, it reads and executes the DOS commands the file contains.

Batch files are useful for issuing frequently used commands whose parameters you have trouble remembering. For example, you can run the Backup program by typing MSBACKUP and then selecting options from the program. But what if you have saved several sets of options in setup files for different circumstances? You can create batch files to run MSBACKUP with the proper setup file when you issue a simple command such as DAILYBAK.

Batch files can echo (display) messages that you designate. This text-display capability is useful for presenting instructions or reminders onscreen. You can compose messages that describe how to execute a command or that contain syntax examples and reminders. Batch files also can use the TYPE command to display text from another file.

In some ways, batch files resemble computer programs. DOS has a host of special commands that are used primarily in batch files. Although you can type some of these commands at the DOS prompt, their main use is in batch files. These commands introduce flow-control and simple decision-making capabilities into a batch file.

Understanding the Contents of Batch Files

Batch files consist entirely of ASCII text characters. You can create batch files in the DOS Editor, in Edlin, and in nearly any other text-editing or word processing program. (If you use a word processing program, you must use a setting that omits the special formatting and control characters that many such programs use for internal purposes.)

The easiest way to create a short batch file, however, is to use the COPY command to redirect input from the keyboard (the CON device) to a file (see Chapter 8, “Managing Your Files,” for more information).

When you create batch files, observe the following rules:

  • Batch files must be ASCII files. If you use a word processing program, be sure that the program saves the file without formatting characters.

  • The name of the batch file, which can be one to eight characters long, must conform to DOS's filename rules. Make batch filenames meaningful so that they are easier to remember.

  • The filename must end with the BAT extension.

  • The filename cannot be the same as a program filename (a file with an EXE or COM extension).

  • The filename cannot be the same as an internal DOS command (such as COPY or DATE).

  • The batch file can contain any valid DOS commands that you can enter at the DOS command line (for example - AUTOEXEC.BAT). (Typos cause errors.)

  • You can include in the batch file any program name you usually type at the DOS command line. DOS executes the program as though you had entered its name at the command line.

  • Use only one command or program name per line in the batch file. DOS executes batch files one line at a time.

You start a batch file by typing its filename (excluding the extension) at the DOS prompt and then pressing Enter. The following list summarizes the rules DOS follows when it executes a batch file:

  • When DOS encounters a syntax error in a batch file's command line, DOS displays an error message, skips the incorrect command, and executes the remaining commands in the batch file.

  • You can stop a batch file by pressing Ctrl+C or Ctrl+Break. DOS displays the following prompt:

    Terminate batch job (Y/N)?
    

    Type N to skip the current command (the one being carried out) and proceed to the next command in the batch file. Type Y to abort execution of the batch file and return to the DOS prompt.

Creating a Simple Batch File

Tasks consisting of the same series of commands are ideal candidates for batch files. One task that you might perform repetitively is copying and comparing files.

In this section, you create a simple batch file, using the COPY command to redirect input from the keyboard (the CON device) to create an ASCII text file. (Remember that you also can use the DOS Editor, Edlin, or another text-editing or word processing program to create ASCII text files.)

Suppose that you often work with two spreadsheet files called SALES.WK1 and CUSTOMER.WK1. You frequently update these files and store them in the directory STORE on drive C. After you update the files, you normally copy them to a disk in drive A and compare the copies on the floppy disk with the originals on the hard disk.

To begin creating a batch file that automates this process, type the following line at the DOS prompt and then press Enter:

COPY CON COPYCOMP.BAT

This COPY command redirects console (keyboard) input to the file COPYCOMP.BAT. After you press Enter, DOS drops the cursor to the line below the DOS prompt at the left of the screen and then waits for further instructions. Type the following three lines, pressing Enter after each line:

@ECHO OFF
COPY C:STORE A:
FC C:STORE A:/L

After you enter the last line in the file, press F6 or Ctrl+Z (both ways produce the characters ^Z on the screen) to send a signal to DOS that the end of the file has been reached. Then, press Enter. DOS copies the three lines into a file named COPYCOMP.BAT and displays the following message:

1 file(s) copied

Note

When you use COPY CON to create a text file, check each line before pressing Enter. You can use Backspace and the DOS command-line editing keys (listed in Chapter 3, “Using DOS Commands”) to edit the current line. After you press Enter, DOS moves the cursor down to the next line, and you cannot correct any errors in previous lines. You can abort the process without saving the file, however, by pressing Ctrl+C.

The first line of the COPYCOMP batch file, @ECHO OFF, instructs DOS not to display the batch file's commands as they are executed. In other words, when you run the batch file, you do not see the command lines themselves onscreen; you see only the results of their actions. The @ sign, just before the word ECHO, instructs DOS not to display that command line, either. Basically, all you need to remember is that @ stops display of the current line, whereas ECHO OFF stops display of all subsequent lines.

The second line of COPYCOMP.BAT copies the desired files from their source location in C:STORE to the destination root directory of drive A.

The final line of the batch file uses FC.EXE, an external DOS command that compares the copied files with the originals. Although you can use the /V (verify) switch with COPY, using FC is more thorough.

Now that the COPYCOMP.BAT batch file is complete, you can run the file by typing the following command at the DOS prompt and then pressing Enter:

COPYCOMP

DOS first copies the two files from the C:STORE directory to drive A and then compares the copies with the original files.

Understanding Replaceable Parameters

The batch files discussed so far in this chapter carry out exactly the same functions every time you use them. You might want a particular batch file to operate on different files each time you use it, even though the commands in the batch file are fixed. When you use replaceable parameters in a batch file, you can use the same commands to perform different tasks.

You already know that a parameter is an additional instruction that defines the task a DOS command will perform. When you type the name of the batch file at the DOS prompt, you can include up to nine parameters. DOS assigns a variable name to each parameter, starting with 1 and going up to 9. (DOS always assigns the variable name 0 to the name of the batch file itself.)

You can use each variable in your batch file by preceding the variable name with the percent sign (%). This combination of the percent sign and variable name is called a replaceable parameter.

When used in a batch file, each replaceable parameter, numbered %0 through %9, holds the place for a parameter in one or more commands of a batch file so that you can provide the actual value of the parameter at the time you execute the batch file.

Consider the COPYCOMP.BAT batch file discussed earlier in this chapter:

@ECHO OFF
COPY C:STORE A:
FC C:STORE A:/L

Each time you execute this batch file, it copies all files from the C:STORE directory to drive A and then compares the files. Suppose that you want to make this batch file more versatile so that you can use it to copy and compare the files in any directory. To do so, revise COPYCOMP.BAT as follows:

@ECHO OFF
COPY %1 %2
FC %1 %2 /L

Notice that %1 and %2 replace C:STORE and A:, respectively. These parameters are the replaceable parameters.

After making these changes in COPYCOMP.BAT, you can use the batch file to copy and compare the files from any directory to any disk or directory. To copy and compare the files in the SPREADSHQPRO4DAT directory on drive C with the files on a disk in drive B, for example, type the following command and then press Enter:

COPYCOMP C:SPREADSHQPRO4DAT B:

DOS copies all files from C:SPREADSHQPRO4DAT to the disk in drive B and then compares the original files with the copies to ensure that the copy procedure was effective.

To see how DOS replaces the parameters, create a batch file called TEST1.BAT that contains the following single line:

@ECHO %0 %1 %2 %3 %4 %5 %6 %7 %8 %9

After you create this file, type TEST1, followed by one space. Then, type your first name, last name, street address, city, state, ZIP Code, and age, with each entry separated by spaces. Then, press Enter. Your screen should look similar to the following:

C:>TEST1 DAVID SMITH 1234 PINE STREET ANYTOWN IN 46032 39
TEST1 DAVID SMITH 1234 PINE STREET ANYTOWN IN 46032 39
C:>

The batch file command instructs DOS to display the parameters 0 through 9. In the preceding example, these parameters are the following:

Parameter Word
%0 TEST1
%1 DAVID
%2 SMITH
%3 1234
%4 PINE
%5 STREET
%6 ANYTOWN
%7 IN
%8 46032
%9 39

Now try to “shortchange” DOS by not specifying a sufficient number of parameters to fill every variable marker. Run TEST1 again, but this time, type only your first name. Your screen should resemble the following example:

C>TEST1 DAVID
TEST1 DAVID
C>

DOS displays the batch filename and your first name. No other information is echoed to the screen. You specified fewer parameters, and DOS replaced the unfilled markers with nothing. In this case, the empty markers did no harm.

Some commands you use in a batch file, however, might require that a replaceable parameter contain a value. If you include DEL in a batch file with a replaceable parameter and the parameter is empty, you see the following error message:

Invalid number of parameters

You can use the IF command (discussed later in this chapter) to avert such errors. In the remainder of this section, you learn how to construct a batch file that takes advantage of replaceable parameters.

Suppose that you use several computers daily, but one of the hard disk systems is your “workhorse,” where you store all the files you want to keep. You use floppy disks to move information from computer to computer. After copying a file back to a hard disk, you usually delete the file from the floppy disk. Deleting the file removes it from the process so that the file is not accidentally copied to the hard disk again later. You use the following steps to transfer data from a floppy disk to a hard disk:

  1. Copy the file from the floppy disk to the hard disk with the verify switch on.

  2. Erase the file from the floppy disk.

To simplify this process, you can create a batch file called C&E.BAT (copy and erase). Type the following commands in the file:

COPY A:%1 C:%2 /V
DEL A:%1

To use the C&E.BAT file, type the following command at the DOS prompt:

C&E oldfilename newfilename

The first parameter, oldfilename, represents the name of the file you want to copy from the floppy disk to the hard disk; newfilename is the new name for the copied file (if you want to change the filename as the file is being copied).

Suppose that you put a disk containing the file NOTES.TXT into drive A and want to copy the file to the hard disk. Type the following command at the DOS prompt:

C&E NOTES.TXT

The screen appears as follows:

C>COPY A:NOTES.TXT C: /V
1 file(s) copied
C>DEL A:NOTES.TXT
C>

Notice that even though you didn't type the parameter newfilename, DOS carried out the batch file, keeping the same filename during the copy. DOS copied NOTES.TXT from drive A to drive C and then deleted the file on the disk in drive A. The %2 parameter was dropped, and the file did not get a new name during the copy operation.

One benefit of creating a batch file that copies a file using parameters is that you can use a pathname as the second parameter. By specifying a pathname, you can copy the file from the floppy disk to a different directory on the hard disk. To copy NOTES.TXT to the WORDS directory, for example, type the following command:

C&E NOTES.TXT WORDS

The screen display is as follows:

C>COPY A:NOTES.TXT C:WORDS /V
1 file(s) copied
C>DEL A:NOTES.TXT
C>

Because WORDS is a directory name, DOS copies the file NOTES.TXT into the directory WORDS, following the rules of syntax for the COPY command. The batch file takes advantage of these syntax rules.

Even if you don't regularly create your own batch files, you can use your knowledge of batch file principles. Many programs are started by batch files rather than by the name of the actual program file. With your knowledge of batch files, you can use the TYPE command to display the contents of any batch file so that you can see what the batch operation is doing.

Many software programs use the commands in an installation batch file to install the main files. You can understand how an installation proceeds if you read the installation batch file. Knowing what the batch file does can help you avert installation conflicts. Suppose that you use drive B to install a program supplied on a 5 1/4-inch disk because your drive A is a 3 1/2-inch drive. Many installation batch files, however, assume that the files are to be installed from drive A. To prevent this conflict, you can modify a version of the installation batch file by changing all instances of A to B. When you run your modified installation batch file, you can install the new software without a hitch.

Working with batch files also can serve as a meaningful introduction to programming. The batch file commands covered in this chapter give batch files the kind of internal flow and decision-making capabilities that programming languages offer. Of course, don't expect batch files to equal the versatility of a full-featured programming environment. But batch files certainly can assume a programming flavor. By using batch files, you can increase DOS's usefulness significantly.

Using Batch File Commands

DOS includes special commands that often are used in batch files. Table 16.1 lists batch file commands.

Table 16.1. Batch File Commands

Command Action
@ Suppresses the display of the command line onscreen
CALL Runs another batch file and returns to the original batch file
CHOICE Halts processing until a specified key is pressed (use the IF ERRORLEVEL command to determine which key was pressed)
ECHO Turns on or off the display of batch commands as they execute; also can display a message onscreen
FOR..IN..DO Permits the use of the same batch command for several files (the execution “loops”)
GOTO Jumps to the line following the specified label in a batch file
IF Permits conditional execution of a command
PAUSE Displays a message and halts processing until a key is pressed
REM Enables you to insert comments into a batch file that describe the purpose of an operation
SHIFT Shifts the command-line parameters one parameter to the left

You can use any of the commands listed in Table 16.1 in a batch file; you can use some of them at the DOS system level, as well. For example, you can type ECHO with or without an argument at the DOS prompt. DOS displays the string you type after ECHO or, if you provide no argument, tells you whether echo is on or off. If you type PAUSE at the DOS prompt, DOS displays the following message and waits for a keystroke:

Press any key to continue

Although these two commands are not very useful at the DOS prompt, the FOR..IN..DO command structure can be quite useful at the operating-system level to carry out repetitive commands (see “Using FOR..IN..DO” later in this chapter).

The following sections explain the batch commands and their uses.

Displaying Messages and Inserting Comments

You already have had an introduction to the ECHO command earlier in this chapter. This command does two things: ECHO ON and ECHO OFF turn on and off the display of lines from batch files as commands are executed, and ECHO also displays messages.

ECHO can display a message up to 122 characters long (the 127-character DOS command-line limit, minus the length of the ECHO command and an additional space).

You can use REM (which stands for remark) in a batch file to remind you what the batch file does. When you review a batch file some time after you create it, you might no longer remember why you used certain commands or why you constructed the batch file in a particular way. Leave reminders in your batch file by using REM statements, which don't appear onscreen when echo is off. The REM comments make the batch file self-documenting, a feature that you and other users will appreciate later.

Tip

The REM function is an important feature to use when you're writing batch files. It is a good idea to include remarks with every section in a batch file explaining what the section is doing, such as copying a file from one location to another. These remarks help explain how the batch file works if others need to modify it.

Another important use of the REM function is to comment out a line in a batch file without actually deleting it. This can prove very useful during troubleshooting problems in a batch file.

If you want the batch file to display particular messages, use ECHO. Messages set with ECHO appear onscreen whether or not you set ECHO OFF. To insert a blank line between messages, type a period (but no space) after the ECHO command, as follows:

ECHO.

Branching with GOTO

When you run a batch file, DOS normally processes commands one line at a time, from the beginning of the batch file to the end. When you use the GOTO command, however, you can change the order in which DOS executes batch commands by instructing DOS to branch to a specific line in the file.

The syntax of GOTO is as follows:

GOTO label

The GOTO command uses label to specify the place in the file to which DOS should branch. A batch file label is a separate line that is not a command, per se. A label consists of a colon followed by one to eight characters. The label name can be longer than eight characters, but DOS reads only the first eight characters.

When DOS encounters a GOTO command in the batch file, it starts at the beginning of the batch file and searches for a label matching the one specified by GOTO. DOS then branches to the batch file line following the label.

Consider the following batch file, LOOP.BAT. This file is similar to the TEST.BAT batch file you created previously, with the addition of the GOTO and PAUSE commands:

@ECHO OFF
:LOOP
   @ECHO Hello, %1
   PAUSE
GOTO LOOP

To test the batch file, type the following and press Enter:

LOOP DAVID

The screen shows the following message:

Hello, DAVID
Press any key to continue_

The batch file begins by echoing Hello, DAVID and then waits for you to press a key. After you press a key, DOS again displays the following message:

Hello, DAVID
Press any key to continue_

When you press a key again, DOS executes the GOTO LOOP command, causing execution of the batch file to return to the line labeled :LOOP at the beginning of the file. DOS again displays the message and pauses.

This batch file is an example of what programmers call an infinite loop. The program never stops on its own. To abort the batch file, you must press Ctrl+C or Ctrl+Break.

This simple example illustrates the operation of GOTO. You seldom will create infinite loops on purpose, but you should be able to use the GOTO command to control the order in which DOS executes batch file commands.

Using the IF Command

The IF command is a “test-and-do” command. When a given condition is true, the IF command executes a stated action. When the given condition is false, IF skips the action. If you are familiar with programming languages, such as BASIC, you should recognize the DOS IF command.

The IF command tests the following three conditions:

  • The ERRORLEVEL of a program

  • Whether a string is equal to another string

  • Whether a file exists

The following sections explain these tests.

Using IF to Test ERRORLEVEL

The first condition that IF can test is ERRORLEVEL. The proper syntax for testing the ERRORLEVEL is as follows:

IF NOT ERRORLEVEL number command

ERRORLEVEL is a code left by a program when it finishes executing. A better name for this condition might be “exit level.” This form of the IF command determines whether the value of ERRORLEVEL is greater than or equal to a number specified in the number parameter. Conversely, by adding the optional word NOT, you can determine whether the value of ERRORLEVEL is not greater than or equal to the value of the number parameter. If the specified condition is true, DOS executes the command specified in the command parameter. Otherwise, DOS skips to the next line in the batch file without executing the command.

The only DOS commands that leave an ERRORLEVEL (exit) code are BACKUP, DISKCOMP, DISKCOPY, FORMAT, GRAFTABL, KEYB, REPLACE, RESTORE, and XCOPY. Many other programs generate exit codes, however.

An exit code of zero (0) usually indicates that the command was successful. Any number greater than 0 usually indicates that something went wrong when the program executed. The following exit codes, for example, are generated by the DISKCOPY command:

Code Meaning
0 The operation was successful.
1 A read/write error that did not terminate the disk-copy operation occurred.
2 The user pressed Ctrl+C.
3 A “fatal” read/write error occurred and terminated the copy procedure before it was completed.
4 An initialization error occurred.

An IF command in a batch file enables you to test for the exit code generated by a DOS command or program to determine whether the command or program worked properly.

When you use ERRORLEVEL to test exit codes, DOS tests whether the code is equal to or greater than the specified number. If the exit code is equal to or greater than the number, DOS executes the command parameter. If the code does not meet the condition, DOS skips the command parameter and executes the next command in the batch file. You can think of this condition as a BASIC-like statement, as follows:

IF exit code >= number THEN do command

The IF ERRORLEVEL command is most useful with the CHOICE command (see “Pausing for Input in a Batch File” later in this chapter). When your batch file uses this utility, the file can pause for keyboard input. The utility puts a value in ERRORLEVEL related to the key pressed. You then can make your batch file branch or perform some other task based on the key pressed. A batch file otherwise does not accept keyboard input except when the input is provided on a batch-file command line.

Suppose that you want to create a batch file named DCOPY.BAT that makes disk copies in your drive A, using the DISKCOPY command and the verify switch. If the disk-copy procedure terminates before completion, you want the batch file to inform you of the cause.

→ For more information about making copies of disks, seeCopying Entire Disks with DISKCOPY,” p. 210.

Create a batch file named DCOPY.BAT that contains the following lines:

@ECHO OFF
DISKCOPY A: A: /V
IF ERRORLEVEL 4 GOTO INIT_ERR
IF ERRORLEVEL 3 GOTO FATL_ERR
IF ERRORLEVEL 2 GOTO CTRL+C
IF ERRORLEVEL 1 GOTO NON_FATL
ECHO DISKCOPY successful and verified!
GOTO END
:INIT_ERR
   ECHO Initialization error!
   GOTO END
:FATL_ERR
   ECHO Fatal error! DISKCOPY stopped!
   GOTO END
:CTRL+C
   ECHO Someone pressed Ctrl+C!
   GOTO END
:NON-FATL
   ECHO A non-fatal error occurred. Check data!
:END

To run this batch file, type DCOPY at the command line and then press Enter. DOS displays the following message:

Insert SOURCE diskette in drive A:
Press any key to continue_

When you press a key, DOS begins the disk-copy procedure. After the DISKCOPY command in the batch file executes, the batch file runs through a series of IF ERRORLEVEL tests. Based on what you already know, these tests are in descending order (4 to 1) because ERRORLEVEL considers any number equal to or greater than the specified number to be a match. Thus, if you were to check for 1 first, 4 would also be a match, and you would never get to the proper test.

First, the batch file tests for an initialization error (exit code = 4). If the exit code equals or is greater than 4, DOS skips to the line labeled :INIT_ERR. If the exit code is 3, execution of the batch file skips to the :FATL_ERR label. The batch file branches to the :CTRL_C label if an exit code of 2 is detected, and to the :NON_FATL label when the exit code is 1.

Finally, if no errors are detected by the series of IF ERRORLEVEL commands, the batch file displays the following message:

DISKCOPY successful and verified!

Using IF to Compare Strings

The second use for the IF command is to test whether string 1 equals string 2. The syntax of the batch command is as follows:

IF NOT string1==string2 command

This form of the IF command determines whether the first character string, string1, is the same group of characters as string2. Usually, one string is a replaceable parameter. If the two strings are identical, this condition is true and DOS executes the command specified in the command parameter. Otherwise, DOS skips to the next line in the batch file without executing the command. By adding NOT to the IF command, you can test for the condition when the two strings are not the same.

Assume that you want to create a batch file named DAYBACK.BAT that backs up your hard disk each day of the week. On Fridays, you want the batch file to perform a complete backup. On Mondays through Thursdays, you want the batch file to perform an incremental backup. Use the DOS Editor or another text editor to create the following batch file:

@ECHO OFF
CLS
IF "%1"=="" GOTO TRY_AGAIN
IF %1==FRI GOTO FULL
IF %1==MON GOTO ADD
IF %1==TUE GOTO ADD
IF %1==WED GOTO ADD
IF %1==THU GOTO ADD
:TRY_AGAIN
   ECHO Try again! Type DAYBACK and day of week (MON-FRI).
   GOTO END
:FULL
   ECHO Insert first disk of backup set.
   PAUSE
   C:
   CD 
   BACKUP C: A: /S
   GOTO END
:ADD
   ECHO Insert last disk of backup set.
   PAUSE
   C:
   CD 
   BACKUP C: A: /S/M/A
:END

To run this batch file, type DAYBACK, followed by the three-letter abbreviation for the day of the week (MON, TUE, WED, THU, or FRI), and then press Enter.

The first IF command in DAYBACK.BAT checks to make sure that you have typed the day of the week. If you don't provide enough parameters with the IF command, DOS replaces the replaceable parameter with a null value. (In batch files, null values must be enclosed in quotation marks to prevent a syntax error.)

The remaining IF commands determine whether you typed FRI or another day of the week. If you type FRI, the batch file branches to the :FULL label and performs a full backup. If you typed MON through THU, the file jumps to the :ADD label and performs an additive incremental backup. If you typed anything else, the batch file instructs you to try again.

Note

The :END label often is used to mark the end of the batch file. In the preceding batch file, execution branches to the :END label after a full backup, after an incremental backup, or after you are instructed to try again. When you use this technique, DOS executes only a portion of the batch file each time you run it, skipping the portions of the batch file that don't apply. Because the :END label is the last line in the batch file, the batch file ends at that point.

In the DAYBACK.BAT example, the replaceable parameter in the first IF command is enclosed in quotation marks because programmers commonly use quotation marks to delimit character strings. Actually, a comparison with any letter, number, or symbol can do the job. One common procedure is to use a single period instead of quotation marks, as shown in the following example:

IF %1. == . GOTO TRY_AGAIN

If you don't enter a parameter for %1, DOS interprets the line as follows:

IF . == . GOTO TRY_AGAIN

Use the syntax that is easiest for you to remember and understand.

If %1 equals nothing, DOS branches to the line following the label TRY_AGAIN and displays a message. If %1 equals something other than nothing, DOS does not branch to TRY_AGAIN; instead, it executes the second IF command in the batch file, which tests whether you typed DAYBACK FRI, and so on. Notice that GOTO statements are used to jump around the parts of the batch file that DOS should not execute.

When you use the IF command, DOS compares strings literally. Uppercase characters are different from lowercase characters. For example, say you run DAYBACK by typing this command:

DAYBACK Fri

DOS compares Fri with the uppercase FRI and decides that the two strings are not the same. The IF test fails, and DOS does not perform the backup operation.

Using IF to Look for Files

The third type of IF command tests whether a given file is on disk. The syntax for this form of the IF command is as follows:

IF NOT EXIST filename command

This form of the IF command determines whether the file specified in the filename parameter exists on your computer's disk (or doesn't exist, if you add NOT). If the file does exist, the IF command executes the command specified in the command parameter.

You can use IF EXIST when you start a word processing program. Perhaps you use a file called TEMP.TXT to store temporary files or write blocks that are to be read into other documents. You can use IF EXIST to test for the existence of the file and erase the file if it does exist.

Your batch file, called WORD.BAT, would look like the following example:

@ECHO OFF
CLS
CD DOCUMENT
IF EXIST TEMP.TXT DEL TEMP.TXT
CD WORDS
WP
CD 

This batch file turns off ECHO and clears the screen. The current directory changes to DOCUMENT—the directory where you store your word processing documents.

Next, the IF command tests for the existence of TEMP.TXT. If the file does exist, DOS deletes the file. Finally, DOS starts your word processing program from the WORDS subdirectory.

Notice the last line of the batch file: CD . When your word processing program starts, the batch file is suspended temporarily. After you quit your word processing program, the batch file regains control. The batch file then executes its last line, CD , which changes back to the root directory. The batch file ends.

Pausing for Input in a Batch File

Before DOS 6.0, the only way to effect the execution of a batch file after the file started was to press Ctrl+C or Ctrl+Break. These key combinations enabled you to cancel a single command or end the entire operation. Starting with DOS 6.0, you are provided a means of temporarily halting the execution of a batch file and accepting limited user input. You can use this feature to decide whether to process certain commands, to branch to a different part of a batch file, or even to present a menu and accept any of a series of choices.

To employ this capability, you use the CHOICE command. The command's syntax is as follows:

CHOICE /C:choices /N /S /T:c,nn message

Following are explanations of the components of this command:

  • /C:choices lists the keys that can be pressed. If you don't specify choices, the default is YN.

  • /N prevents the display of acceptable keys at the end of the prompt.

  • /S instructs CHOICE to pay attention to the case of the key pressed; this feature enables you to use Y and y for different choices.

  • /T:c,nn causes CHOICE to act as though you pressed the key represented by c if you don't make a choice within nn seconds.

  • message is the optional prompt to display.

You respond to the key pressed by using a series of IF ERRORLEVEL commands. By default, the choices are Y and N. Y has the ERRORLEVEL code 2, and N has the ERRORLEVEL code 1.

Making a Two-Way Choice

If you don't specify which keys should be pressed, CHOICE assumes Y and N, and adds [Y,N]? to the end of whatever message you choose to include. This feature is extremely useful if you want to decide whether to load a certain program when your computer starts. For example, you might type the following commands near the end of your AUTOEXEC.BAT file:

CHOICE Back up hard disk
IF ERRORLEVEL 2 MSBACKUP

When the AUTOEXEC.BAT file reaches the first line, DOS displays the following message:

Back up hard disk[Y,N]?

If you have not yet backed up your hard disk today, you type Y, which generates the ERRORLEVEL code 2. DOS then executes the MSBACKUP program. If you have backed up your hard disk, type N. You need not test for this code, however, because it's the only other alternative. DOS then executes any commands following these lines in AUTOEXEC.BAT, but MSBACKUP doesn't run.

Creating a Simple Menu

Because you can specify any keys as choices, you can use CHOICE to create a simple menu, using the /C:choices parameter to specify the keys to be pressed. You might use a command such as the following:

CHOICE /c:swd Load Spreadsheet, Word Processor, or Database Manager

DOS displays the following message:

Load Spreadsheet, Word Processor, or Database Manager[S,W,D]?

The ERRORLEVEL codes for the specified keys read from left to right. Thus, pressing D generates a code 3; pressing W, a code 2; and pressing S, a code 1. These exit codes are then processed by batch file lines such as the following:

IF ERRORLEVEL 3 DB
IF ERRORLEVEL 2 WP
IF ERRORLEVEL 1 SS

This assumes that your database program is named DB, your word processor is named WP, and your spreadsheet is named SS. There is a problem with this, however. The IF ERRORLEVEL command automatically assumes that all numbers higher than the one specified also are true. If you type D, for example, DOS loads your word processing program as soon as you exit from your database manager and your spreadsheet program as soon as you exit from your word processing program.

You can deal with this situation in either of two ways. One way is to add a second command that changes the flow of execution. Your file would have to resemble the following example:

CHOICE /C:swd Load Spreadsheet, Word Processor, or Database Manager
IF ERRORLEVEL 3 DB
IF ERRORLEVEL 3 GOTO END
IF ERRORLEVEL 2 WP
IF ERRORLEVEL 2 GOTO END
IF ERRORLEVEL 1 SS
:END

The second way to deal with the limitation of the ERRORLEVEL directive is to have each test execute a batch file instead of a program. (After you pass control to a second batch file, DOS does not return to the original file unless you use CALL or COMMAND /C.) For this command to work properly, the batch files must appear either in the current directory or in a directory in the path that precedes the directories containing the programs.

Always give a user a way to get out of a command without choosing any of the proffered alternatives. The user, of course, can break out of the CHOICE command by pressing Ctrl+C or Ctrl+Break. But you also can include a third alternative, such as Quit, as shown in the following example:

CHOICE /C:YNQ Back up hard disk
IF ERRORLEVEL 3  GOTO END
IF ERRORLEVEL 2  GOTO END
IF ERRORLEVEL 1  MSBACKUP
other commands
:END

Creating a Simple Display Menu

You can use the other switches provided with CHOICE to create a display menu. You create text to explain the choices and suppress the display of characters at the end of the optional message. You might create a batch file called MENU.BAT and type the following commands:

@ECHO OFF
CLS
ECHO;
ECHO;
ECHO Press S to load Spreadsheet
ECHO Press W to load Word Processor
ECHO Press D to load Database Manager
ECHO Press Q to quit
ECHO;
CHOICE /C:SWDQ /N /T:Q,10 Your choice?
IF ERRORLEVEL 4 GOTO END
IF ERRORLEVEL 3 GOTO DB
IF ERRORLEVEL 2 GOTO WP
   ECHO Loading spreadsheet program_
   SS
   GOTO END
:WP
   ECHO Loading word processing program_
   WP
   GOTO END
:DB
   ECHO Loading database management program_
   DB
:END

Notice that no ERRORLEVEL choice is available for times the user presses S (the ERRORLEVEL would be 1) because there is no need to branch in this case. Instead, execution of the batch file falls through to the first line after the last ERRORLEVEL statement, which is the command for the spreadsheet section.

When you type the MENU command, DOS clears the screen and displays the following message:

Press S to load Spreadsheet
Press W to load Word Processor
Press D to load Database Manager
Press Q to quit
Your choice?

If no key is pressed within 10 seconds, the CHOICE command issues a Q, and the DOS prompt returns.

You can construct very elaborate menus by using the ASCII box-drawing characters, ANSI Escape sequences (to establish colors), and the CHOICE command.

→ For a discussion of the uses of ANSI.SYS, see Chapter 17, “Understanding ANSI.SYS,” p. 415.

Using FOR..IN..DO

FOR..IN..DO is an unusual and extremely powerful batch command. The command's syntax is as follows:

FOR %%variable IN (set) DO command

variable is a one-letter name that takes on the value of each item in set. You can use this command from the DOS prompt as well as within a batch file. When you use the command at the DOS prompt, however, use only one percent sign (%) instead of two (%%) in front of variable. You must use two percent signs in a batch file so that DOS does not confuse variable with a replaceable parameter.

The set parameter is the list of items, commands, or disk files whose value you want variable to take. You can use wildcard filenames with this parameter. You also can use drive names and paths with any filenames you specify. If you have more than one item in the set, use a space or comma between the names.

The command parameter is any valid DOS command that you want to perform for each item in set.

Using a FOR..IN..DO Batch File

An interesting example of the use of FOR..IN..DO is a batch file that compares filenames found on a disk in drive A with the filenames found on another disk and then produces a list of the files on both disks. Create the batch file CHECKIT.BAT, entering the following lines:

@ECHO OFF
CLS
IF "%1"=="" GOTO END
FOR %%a IN (B: C: D: E: b: c: d: e:) DO IF "%%a"=="%1" GOTO COMPARE
ECHO Syntax error: You must specify a disk to compare.
ECHO Be sure to leave a space before directory.
GOTO END
:COMPARE
   %1
   IF "%2"=="" GOTO SKIP
   CD %2
:SKIP
   ECHO The following files are on both disks:
   FOR %%a IN (*.*) DO IF EXIST A:%%a ECHO %%a
:END

Insert into drive A the disk that you want to compare and then use the following syntax:

CHECKIT drive directory

drive is the drive that contains the other disk that you want to compare, and directory is the directory that you want to compare. This batch file substitutes the drive you specify for %1 in the batch file commands and substitutes any directory you specify for %2. The directory is optional; if you specify a drive and directory, separate their names with a space. Otherwise, the batch file treats the drive and directory as one replaceable parameter (%1). If you don't specify a directory name, DOS compares the current directory of the drive with the current directory of the disk in drive A.

Suppose that you want to compare the list of files in drive A with the list of files in the GAMES directory in drive B. Type the following command at the command line:

CHECKIT B: GAMES

The batch file determines which files in the GAMES directory of the disk in drive B also are on the current directory of the disk in drive A.

When the CHECKIT batch file is called, DOS first determines whether %1 is empty. (%1 is empty if you typed no drive letter or directory after CHECKIT in the command line.) If %1 is empty, the batch file displays an error message, branches to the end of the file, and quits without performing a comparison.

If you specify a disk drive, DOS goes to the third line of the batch file and determines whether the drive letter is a valid drive letter. In this batch file, valid drive letters are B, C, D, E, b, c, d, and e. If no valid drive letter is found, or if you don't include a colon (:) and space after the drive letter, the batch file displays a message and branches to the end of the batch file.

If you specified a valid drive, CHECKIT branches to the :COMPARE section of the program. When executing the first line in this section, DOS logs on to the drive you specified in the command line (the drive designation replaces %1 in the batch file). The batch file determines whether you included a directory parameter; if you did include this parameter, DOS changes to that directory.

Finally, the batch file displays a message and then looks at all the filenames in the current directory to see whether a file with the same name exists in drive A. For every match found, the batch file lists the filename.

Using FOR..IN..DO at the DOS Prompt

You might find that you want to issue commands such as the ones in CHECKIT at the DOS prompt. Instead of using the batch file for the preceding example, you can change subdirectories manually and then type the FOR..IN..DO line (the line that does all the work in the batch file) at the DOS prompt. If you do use FOR..IN..DO outside a batch file, DOS requires that you enter only one percent sign.

Using FOR..IN..DO with Other Commands

FOR..IN..DO works as well with commands as with filenames. Instead of naming a set of files, you can name a series of commands that you want DOS to carry out. Consider the following example:

FOR %%a IN (COPY DEL) DO %%a C:*.*

In a batch file, this line first copies all the files on drive C to the current directory and then erases the files from drive C. Instead of specifying the drive and file, you can use a replaceable parameter in the line, as follows:

FOR %%a IN (COPY DEL) DO %%a %1

To use this batch file, you first must change to the destination directory (for example, D:BAK). When you invoke this version of the batch file, you type the names of the files that you want to copy and remove. If you name the batch file MOVER.BAT, you can type the following command to invoke the file:

MOVER C:WP

MOVER.BAT copies all the files in the subdirectory C:WP to D:BAK and then erases the files in C:WP. This file works much like the C&E.BAT file you created earlier in this chapter.

Moving Parameters with SHIFT

The SHIFT command moves the parameters in the command line that invoked the batch file; each parameter moves one parameter to the left. SHIFT tricks DOS into accepting more than 9 replaceable parameters (10 if you include the batch filename, which is %0). The diagram of SHIFT is as follows:

%0  ←%1  ←%2  ←%3  ←%4  ←%5...
↓
bit bucket

In this diagram, parameter 0 is dropped. The old parameter 1 becomes parameter 0. The old parameter 2 becomes parameter 1; parameter 3 becomes 2; parameter 4 becomes 3; and so on. A command-line parameter that previously was 10th in line and not assigned a parameter number now becomes parameter 9.

The following batch file, SHIFTIT.BAT, is a simple example of the use of the SHIFT command:

@ECHO OFF
CLS
:START
ECHO %0 %1 %2 %3 %4 %5 %6 %7 %8 %9
SHIFT
PAUSE
IF NOT "%0"=="" GOTO START

Suppose that you type the following text:

SHIFTIT A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

The screen shows the following message:

SHIFTIT A B C D E F G H I
Press any key to continue_

Notice that the batch filename is displayed because %0 holds the name of the batch file. Press a key to continue; DOS now displays the following message:

A B C D E F G H I J
Press any key to continue_

In this case, the filename has been dropped into the bit bucket. %0 now equals A. All the parameters have shifted one to the left. Each time you press a key to continue, SHIFT continues moving down the list of parameters you typed. When the leftmost parameter (%0) is empty, the batch file ends.

SHIFT has many uses. You can use it to build a new version of the C&E.BAT file you created earlier in this chapter. The following modified version of the copy-and-erase batch file, called MOVE.BAT, shows a use for SHIFT:

@ECHO OFF
CLS
:LOOP
COPY %1 /V
ERASE %1
SHIFT
IF NOT "%1" == "" GOTO LOOP

This batch file copies and erases the specified file or files. The batch file assumes nothing about the files to be copied; you can specify a disk drive, path, and filename. The batch file copies the files to the current directory and then erases the files from the original disk or directory.

The last two lines shift the parameters to the left, determine whether any parameters remain, and then repeat the operation if necessary.

Running Batch Files from Other Batch Files

On some occasions, you might want to run a batch file from another batch file. Running batch files from within batch files is particularly useful when you want to create a menu batch file that can start several different programs.

The following sections discuss three ways to run batch files from other batch files. One method is a one-way transfer of control. The other two methods involve running a second batch file and returning control to the first batch file. These techniques are useful if you want to build menus with batch files or use one batch file to set up and start another batch file.

Shifting Control Permanently to Another Batch File

The first method of calling a second batch file is simple: Include the root name of the second batch file as a line in the first batch file. The first batch file runs the second batch file as though you had typed the second batch file's root name at the DOS prompt.

To run BATCH2.BAT, for example, include in BATCH1.BAT the following line:

BATCH2

DOS loads and executes BATCH2.BAT. Control passes in only one direction: from the first batch file to the second. When BATCH2.BAT finishes executing, DOS displays the system prompt. Control goes to the second file but doesn't come back to the first file.

Calling a Batch File and Returning Using CALL

After your batch file is debugged, you can use the CALL statement to run a batch file and then return to the original one. The syntax of the CALL command is as follows:

CALL filename parameters

filename is the root name of the batch file. When you type the CALL command, you can specify any parameters that you want to pass to the batch file you are calling. You can place the CALL command anywhere in the first batch file.

When DOS executes a CALL command, DOS temporarily shifts execution to the called batch file. As soon as the called batch file is completed, DOS returns to the first batch file and continues execution with the line immediately following the CALL command.

The following three batch files demonstrate how CALL works:

BATCH1.BAT

@ECHO OFF
CLS
REM This file does the setup work for
REM demonstrating the CALL command.
ECHO This is the STARTUP batch file
ECHO The command parameters are %%0-%0 %%1-%1
CALL batch2 second
ECHO MEM from %0
MEM
ECHO Done!
BATCH2.BAT

ECHO This is the SECOND batch file
ECHO The command parameters are %%0-%0 %%1-%1
CALL batch3 third
ECHO MEM from %0
MEM


BATCH3.BAT

 ECHO This is the THIRD batch file
ECHO The command parameters are %%0-%0 %%1-%1
ECHO MEM from %0
MEM

The first line of BATCH1.BAT sets ECHO OFF. The second line clears the screen. The next two lines in BATCH1 are remarks intended only to document the purpose of the batch file.

The two ECHO lines are similar for all three batch files. The first of the two lines identifies the batch file being used. The second ECHO line shows the %0 parameter (the name by which the batch file was invoked) and the first parameter (the first argument) for the batch file. Notice that to display the strings %0 and %1, you must use two percent signs (%%0 and %%1). If you use a single percent sign, DOS interprets the string as a replaceable parameter and does not display the actual percent symbol.

Each CALL statement in the first and second batch files invokes another batch file. BATCH1.BAT calls BATCH2.BAT, and BATCH2.BAT in turn calls BATCH3.BAT. In each case, a single argument passes to the batch file being called: second to BATCH2.BAT and third to BATCH3.BAT. Each batch file then displays its name (by using the %0 variable) and runs MEM. When DOS reaches the end of each called batch file, DOS returns to the calling batch file.

Check the printout or screen display for the largest executable program size provided by the MEM command (in other words, the largest block of memory available for use by an executable program). This number grows larger after each batch file is executed and removed from memory.

Each time you use the CALL command, DOS temporarily uses 80 bytes of RAM until the called batch file finishes running. Because DOS uses that much memory for each nested CALL command, you can run out of memory. (A nested CALL command is a CALL command from a called batch file.) Not many people nest CALL commands deeply in batch files. The accumulated memory-usage problem does not occur when a single batch file calls multiple other batch files. In that case, you can use the CALL command as many times as you want and use only the same 80 bytes of RAM for each call.

Using COMMAND.COM to Execute a Batch File

In all versions of DOS, you can call a second batch file from the first, execute the second batch file, and return to the first batch file. In DOS 3.0 through 3.2, you use COMMAND /C. In DOS 3.3 and later versions, you use the CALL command, discussed in the following section.

→ For more information on COMMAND /C, seeLoading a Secondary Command Processor,” p. 288.

Although it might appear at first glance that you no longer need to use the COMMAND.COM method of running a batch file, beginning with DOS 6.2 there is a compelling new reason. That is, with DOS 6.2, you can use COMMAND.COM's /Y switch, in conjunction with /C, to single-step through a batch file. Suppose you execute the following command line:

COMMAND /Y /C NEW.BAT

When you do so, DOS loads a copy of the command processor and executes NEW.BAT. As it executes, each line in the batch file is displayed, and you are asked whether you want to execute it. You use this same process when you interactively execute the AUTOEXEC.BAT file, as described in Chapter 2, “Starting DOS.”

This interactive execution capability is a great debugging tool for complex batch files. When the entire batch file is through running, DOS exits the command processor and returns to the original batch file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.144.229