Batch Files 101 By Ken Johnson, Chicago Computer Society This month's column will look at Batch files. We'll introduce batch files, how they work, and the batch "language". Next month we'll put it all together and look at some practical batch files that use the techniques discussed here. A batch file is simply a text file that contains DOS commands and/or programs to run. Batch files can easily be identified by their ".BAT" file extension. To execute a batch file, you simply enter the name of the file (without the .BAT). DOS will look at each line in the file and execute the command or program it finds there -- just as if you had typed them in yourself. You probably are familiar with at least one batch file, AUTOEXEC.BAT. This is the batch file that DOS looks for (and executes) every time you boot up the computer. You can use AUTOEXEC.BAT to load TSR programs, set your search path and DOS prompt, execute a DOS shell or menu program, or otherwise to configure the computer the way you want. But most PC users have several other batch files they constantly use. Why use batch files? Because they can save you time and effort. If you type a series of commands (or one long command) repeatedly, create a batch file to do the typing for you. This makes batch files particularly useful to new users, since they can execute programs without having to remember all the appropriate DOS commands or program switches. Batch files also can make it easier to perform repetitive jobs like backing up your hard disk. If you know that you can simply enter BKUP to do a backup, rather than having to remember a long and complicated sequence of commands, you're more likely to do it! Creating a Batch File Since batch files simply contain text, there are several ways to create them. The simplest and easiest is probably to use a text editor that saves it's files as ASCII text. This means that the file contains no hidden formatting codes, just straight text. A popular shareware text editor is QEdit, which can be downloaded from the CCS Bulletin Board as QEDIT21.ZIP. You also can use your favorite word processor to create batch files. Since most word processors insert formatting codes, make sure to save your file as "standard text" or "DOS text". For example, in WordPerfect you would select Text In/Out (CTRL-F5), then DOS Text (1), then Save (1). For short batch files, you can create the file directly from the keyboard. You use a special version of the COPY command to copy text directly from the keyboard into the file. The DOS reserved word CON (or CONsole) means the keyboard; what you are doing is using the keyboard as your "source file" for the copy. On the DOS command line, enter: COPY CON filename.BAT where filename is the name of your batch file (don't forget the .BAT file extension!). The cursor will drop down a line, and you can start typing. Press Enter after each line, then press the F6 key when done. This will insert DOS' end-of-file marker (a "^Z"), and you'll see the "1 file(s) copied" message. For example, let's create a batch file called DIRAB.BAT that will clear the screen then display the directory of both floppy drives. Enter the following: COPY CON DIRAB.BAT ΔΩ CLS ΔΩ DIR A: ΔΩ DIR B: ΔΩ ^Z ΔΩ The "ΔΩ" indicates that you press Enter at the end of each line. Remember that you don't type the "^Z" at the end; you enter it by pressing the F6 key. While COPY CON is a quick way to create a batch file, it isn't exactly user friendly in operation. You enter one line at a time in sequential order, and after you press Enter you cannot go back and edit a line. If you make a mistake, you can abort the copy by holding down the Ctrl key and pressing the C key (Ctrl-C), then trying it again. After creating a batch file, you should reread it to make sure it contains all the commands you want, and in their proper form. The easiest way is to TYPE the file to the screen: TYPE DIRAB.BAT Running the Batch file To execute a batch file, just enter it's name without the .BAT extension: C>DIRAB A batch file will execute one line at a time. The commands execute sequentially (top to bottom), though you can "jump around" in a batch file with the GOTO statement discussed below. If you want to stop a batch file, hold down the Ctrl key and press the C key or the Break key (Ctrl-C or Ctrl-Break). DOS will ask "Terminate batch job (Y/N)?". Type Y and you'll return to the DOS prompt. Remember that all batch files have to have the .BAT file extension. Make sure that you do not give your batch file the same name as a DOS command or an executable file (a .COM or .EXE file). When you enter something on the DOS command line, DOS first checks to see if what you entered is one of it's internal commands (such as DIR, COPY, TYPE, etc.). If DOS doesn't find an internal command that matches what you typed, it then checks for a COM file with the same name, then an EXE file with the name, and finally a BAT file with the name (in that order). So if I called the batch file above DIR, it would not execute since DOS would assume I wanted it's own DIRectory command when I typed in "DIR". Batch Parameters One powerful feature of batch files is the ability to include parameters that are passed to the batch file when it executes. This capability makes it possible to create flexible and reusable batch files that can accept input from the user and act accordingly. Then DOS executes a batch file it examines the command line, looking for delimiters such as spaces or commas that divide what you've entered into discrete elements. DOS then assigns these elements to up to ten variables, or parameters. These parameters are in the form %N, where N is a number from 0 to 9. As a batch file executes, each occurrence of %N is replaced by the corresponding string from the DOS command line. %0 corresponds to the first thing you typed, which is always the name of the batch file itself. For example, suppose the batch file EDCOPY.BAT contains: WP %1 XCOPY %1 %2 When you execute the DOS command: C>EDCOPY BUDGET.DOC B: each %1 is replaced with BUDGET.DOC and each %2 is replaced by B: WP BUDGET.DOC XCOPY BUDGET.DOC B: The Batch Subcommands The Batch programming "language" is made up of just a handful of commands, which are sometimes called subcommands. The language isn't very refined, but it can be very powerful once you understand how it works. Like other computer languages, the batch subcommands allow you conditionally to execute parts of the program, loop through commands, use variables with changeable values, and call other batch programs. The batch subcommands are CALL, ECHO, FOR, GOTO, IF, PAUSE, REM, SHIFT, and @. ECHO Subcommand ECHO can be used to display a message to the user or tells DOS whether to display normal messages during the execution of batch file. The forms of ECHO are: ECHO [message] or ECHO [ON or OFF] ECHO OFF -- Halts the display of the DOS prompt and keeps DOS from displaying the lines of the batch file as they are executed. But, ECHO OFF does not prevent the DOS command's or program's output from being displayed. ECHO ON -- Restores normal display activity. This is the default. ECHO message -- Displays the indicated message. You can fancy up the screen by including borders or boxes as part of the message. ECHO entered by itself will display the ECHO status (ON or OFF). One batch file trick is to use the CLS (CLear Screen) command immediately after ECHO OFF to get an uncluttered screen. The @ Operator Unfortunately, when the batch file executes ECHO OFF, the ECHO OFF command itself echoes to the screen. But if you are using DOS 3.3 or later, you can prevent the ECHO OFF from displaying by including an @ sign at the beginning of the command like so: @ECHO OFF. The "@" can be prefixed to any DOS command, program name, or batch file name. It makes the command silent -- the command itself is not echoed to the screen but the output will be displayed. You can think of @ as a one-line-only version of ECHO OFF. REM Subcommand REM (REMark) is used to add comments to a batch file. The REMarks may or may not be displayed on the screen, depending on whether ECHO is ON or OFF. REMarks are handy ways of reminding yourself what the batch file does, as well as documenting your program for others. The form of the statement is: REM [remark] The remark can be up to 123 characters in length. If ECHO is ON, the remark will be displayed on the screen; if ECHO is OFF, it will not be seen. Since a displayed REMark will include the DOS prompt as well as the REM subcommand, REM is most often used with ECHO OFF. If you need to display text to the user, the ECHO command provides a "cleaner" way to do so. PAUSE Subcommand PAUSE momentarily stops the batch file execution, displays a message, and wait for the user to press any key. Whenever you ECHO a message to the screen, you'll probably want to include a PAUSE immediately after the ECHO to give the user time to read it. You also can use PAUSE to tell the user how to terminate the program with a CTRL-Break before it starts a critical operation. The form of the statement is: PAUSE The program stops and DOS prompts with "Press a key when ready. . ." Let's look at a sample program to delete backup files, which allows the user to stop the program before the deletions takes place: ECHO OFF ECHO I'm about to delete all .BAK files. Press Ctrl-Break to stop. PAUSE DEL *.bak GOTO Subcommand This powerful command causes DOS to begin executing a different part of the batch file. Execution will jump to another part of the file identified by a unique label. This label must start with a colon and must be the first thing on the line. The form of the GOTO statement is: GOTO line_label Execution restarts at the batch file line that contains the "line_label". You don't have to include the colon with the label on the GOTO statement. Labels are not case sensitive, and you can have labels that are not matched with GOTO statements (DOS treats them as REMarks). Since batch files are executed sequentially top to bottom, frequently you'll use GOTO to jump over some commands, loop backward to reexecute some commands, or jump to the end of the program. In complex batch programs its common to end with an ":END" label and include several GOTO END statements to jump there when appropriate. Let's look at some examples: :AGAIN <-- this is the line label ECHO This is an infinite loop!! ECHO Press Ctrl-Break to stop . . . GOTO AGAIN <-- this causes the loop Here's another: ECHO OFF IF "%1" == "" GOTO noname ECHO File information on file %1 DIR %1 GOTO end :noname ECHO You must supply a file name! ECHO Please try again . . . :end In this last example you are using GOTO to handle an error message. The batch file expects the user to enter a filename. If nothing is entered, then the parameter "%1" is blank and the file jumps to the ":noname" label, displaying a message. If a file name is entered, then the program displays directory information for that file. But then the program has to jump over the error message, since it is clearly not appropriate if a name was given. The "GOTO end" does this. IF Subcommand IF will execute or skip a batch command, depending on one of three conditions. The capability to have conditional execution is what can give batch files real power. The forms of the IF statement are: IF [NOT] EXIST filespec command or IF [NOT] string1 == string2 command or IF [NOT] ERRORLEVEL number command The NOT modifier specifies that the "command" is to be executed if the condition is false. "command" is any DOS command, batch file, or program name. "EXIST filespec" is true when a file with the filename and extension exists on the specified (or default) drive. A wildcard filespec makes the condition true if any file matches the wildcard. "string1 == string2" is true when string1 and string2 are identical. This test is case sensitive, and notice you use two equals signs. One important use of this form of IF is processing of the replaceable parameters: IF "%1" == "A:" GOTO doa IF "%1" == "a:" GOTO doa IF "%1" == "B:" GOTO dob IF "%1" == "b:" GOTO dob IF "%1" == "" GOTO noparm (Sting comparisons will result in a syntax error if either string is blank, so enclose both strings in quotes.) "ERRORLEVEL number" is true when the DOS environmental variable ERRORLEVEL is equal to or greater than the number specified. ERRORLEVEL is really a poor name, because it does not necessarily indicate an error. It is a way for programs to communicate to DOS (or your batch file) what happened when they ran. "Return code" might be a better name; different ERRORLEVEL values can indicate successful and unsuccessful completion, and for unsuccessful completion what error occurred. Some examples of the various ways you can harness the power of IF: IF NOT EXIST d:customer.db copy c:\pdoxdata\customer.db d: Copies CUSTOMER.DB from the PDOXDATA subdirectory on the C: drive to drive D: but only if it is not already on the D: drive. IF "%1" == "LTRS" cd c:\wp51\ltrs IF "%1" == "ltrs" cd c:\wp51\ltrs Sets the default directory to \WP\LTRS if the first batch parameter is "LTRS" or "ltrs". BACKUP c:\*.* a: /s IF ERRORLEVEL 3 goto TROUBLE If the BACKUP command terminates with an exit code of 3 or higher, control will branch to the label :TROUBLE. The last three batch subcommands are a little more advanced, but they will give you an idea of the powerful capabilities of the batch language: FOR . . .IN . . .DO Subcommand The FOR subcommand allows a DOS command to be repeated multiple times. On each repeat, a batch variable gets set to a filename from a specified list. The format of the statement is: FOR %%x IN (list) DO command %%x -- is the variable name. "x" is a letter, A-Z. list -- is a sequence of filenames, separated by commas or spaces. The parenthesis are required. A wildcard filespec works like a list of all filenames that match the wildcard. command -- is any DOS command or program name (except a FOR command) For each item in "list", the variable %%x takes on the value of that item when the command is executed. The idea is to use %%x in the "command" to modify the command action on each repetition. For example: FOR %%d IN (a,c,d) DO dir %%d:*.* displays directories of drives A, C, and D sequentially. This would be the same as entering: dir a:*.* dir c:*.* dir d:*.* SHIFT Subcommand The SHIFT statement changes each batch parameter to the value of the next higher one. In other words, each parameter moves down one: %1 becomes %0, %2 becomes %1, et cetera. SHIFT allows a batch file to have more than 9 parameters -- you simply SHIFT them down to act upon them. CALL Subcommand The CALL subcommand is available starting with DOS 3.3 and is used to execute one batch file from inside another. When the second batch file is finished, control resumes in the first at the statement immediately following the CALL command. We've introduced batch files and looked at the batch language. In next month's Beginner's Column we'll see these Batch techniques and commands in action. We'll look at some useful batch files and see how they work, and how you might modify them for your use.