batch.files.explained

44
batch_files_explained.txt 26/02/2002 The Power of PC/MS-DOS Batch Files Part 1: Getting Started One of the keys to getting the most from your IBM-compatible computer is learning to make the most of the operating system. PC/MS-DOS, while not as simple to learn as the operating systems for some other computers, has the potential to let you customize your computing and increase your productivity. When Microsoft designed the original PC/MS-DOS, the personal computer was still something of an unknown quantity. Few people anticipated the millions of personal computers that would be sold. Fortunately for users, PC/MS-DOS included a powerful capability: batch processing. This series of articles will explore the depths of PC/MS-DOS batch processing, teaching you how to automate many of the functions of your PC. You'll also learn how to use batch files to make your PC do things you never thought possible. BATCH FILE BASICS There are three types of programs that PC/MS-DOS can run directly. You are already familiar with two of them. Files with the extensions .COM and .EXE run when you enter the filename at your system prompt. Batch files, with the extension, .BAT, are the third type. A batch file is nothing more than a series of DOS commands, separated by carriage returns. When you enter the name of the batch file, DOS carries out the commands, one at a time. Once a batch file is running, you can stop it by holding down the <Ctrl> key while you press the <Break> key. If you do this, a message will appear on the screen: Terminate batch job (Y/N)? If you press a Y, the batch file will abort. Pressing N continues the batch file's operation. Page 2 You can use any DOS command in a batch file, from simple ones like COPY to commands seldom used, like ASSIGN. When you call a batch file by entering its file name, PC/MS-DOS opens the file, and carries out the first command. Once the operation of that command is completed, the system prompt (A>, C>, etc.) reappears, and the next command in the batch file executes automatically. There is no limit to the length of a batch file. The computer will continue to carry out the commands until it reaches the end of the file. CREATING BATCH FILES There are five basic requirements for the structure of any 1

Upload: bzanaj

Post on 11-Mar-2015

338 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Batch.files.explained

batch_files_explained.txt 26/02/2002

The Power of PC/MS-DOS Batch Files

Part 1: Getting Started

One of the keys to getting the most from your IBM-compatiblecomputer is learning to make the most of the operatingsystem. PC/MS-DOS, while not as simple to learn as theoperating systems for some other computers, has thepotential to let you customize your computing and increaseyour productivity.

When Microsoft designed the original PC/MS-DOS, the personalcomputer was still something of an unknown quantity. Fewpeople anticipated the millions of personal computers thatwould be sold. Fortunately for users, PC/MS-DOS included apowerful capability: batch processing.

This series of articles will explore the depths of PC/MS-DOSbatch processing, teaching you how to automate many of thefunctions of your PC. You'll also learn how to use batchfiles to make your PC do things you never thought possible.

BATCH FILE BASICS

There are three types of programs that PC/MS-DOS can rundirectly. You are already familiar with two of them. Fileswith the extensions .COM and .EXE run when you enter thefilename at your system prompt. Batch files, with theextension, .BAT, are the third type.

A batch file is nothing more than a series of DOS commands,separated by carriage returns. When you enter the name ofthe batch file, DOS carries out the commands, one at a time.

Once a batch file is running, you can stop it by holdingdown the <Ctrl> key while you press the <Break> key. If youdo this, a message will appear on the screen: Terminatebatch job (Y/N)? If you press a Y, the batch file willabort. Pressing N continues the batch file's operation.

Page 2

You can use any DOS command in a batch file, from simpleones like COPY to commands seldom used, like ASSIGN. Whenyou call a batch file by entering its file name, PC/MS-DOSopens the file, and carries out the first command. Once theoperation of that command is completed, the system prompt(A>, C>, etc.) reappears, and the next command in the batchfile executes automatically.

There is no limit to the length of a batch file. Thecomputer will continue to carry out the commands until itreaches the end of the file.

CREATING BATCH FILES

There are five basic requirements for the structure of any

1

Page 2: Batch.files.explained

batch_files_explained.txt 26/02/2002

batch file:

1. It must be a pure ASCII file, meaning that no charactersother than the commands you give, plus carriage returns, canbe used in the file.

2. The filename can be any legal filename, but cannot havethe same name as a .COM or .EXE file in the same directory,or the same name as any DOS internal command, such as COPYor DIR.

3. It must have the extension .BAT.

4. The file must have an end-of-file marker following thelast command in the file.

5. Each command must be on a separate line in the batchfile, separated from adjacent commands by a carriage return.

Creating an actual batch file is simple. There are twobasic methods I recommend. Each has its advantages anddisadvantages.

The first method uses the DOS COPY command. Use this methodfor creating short, simple batch files. First, give thecommand: COPY CON [DRIVE][PATH][FILENAME]. Here's a samplecommand:

COPY CON C:\BATCH\STARTUP.BAT <Enter>

This command will create the file, STARTUP.BAT, in the\BATCH directory in drive C:. When you press <Enter> thecursor will move to the next line on the screen and you canbegin writing your batch file.

Type in the first command in your series of commands. Youcan correct your spelling by backspacing and retyping, aslong as the cursor is on the current line. When the line iscorrect, press <Enter> to move the cursor to the next line.

Page 3

Now type in additional commands, as needed for your batchfile, following each line by pressing <Enter>. This adds acarriage return character to the end of the line, tellingPC/MS-DOS to carry out the command on that line.

Once you have typed in all the commands to be used in thatparticular batch file, press <Enter> once more at the end ofthe last line. Now press <F6> or hold down the <Ctrl> keywhile you press the <Z> key. Either operation will place anend-of-file character in your file. Press <Enter> again andthe computer will write the file to the disk.

Test this procedure by creating a batch file which displaysa directory. Follow the steps below to create this file inthe current drive and directory. At the system prompt,type:

COPY CON D.BAT <Enter>DIR <Enter><F6> or <Ctrl>+<Z> <Enter>

2

Page 3: Batch.files.explained

batch_files_explained.txt 26/02/2002

Your drive light will come on, and the file will be writtento disk. Now, check your work and test the file. Press the<D> key, then press <Enter>. You should see a directory onyour monitor. Notice that you have simplified the commandwhich displays a directory. Now you only have to type asingle letter, instead of three.

While the COPY CON method works fine, it's not as convenientfor longer batch files which might contain many commands.If you make a mistake with the COPY CON method, there is noway to fix it. You have to retype the entire batch file.For this reason, use this method only for short, simplefiles.

When you need to create a longer batch file, use a texteditor. Just about any text editor or word processingprogram will work. The only requirement is that the editormust be able to save pure ASCII files.

If you use PC-WRITE, your batch files will automatically besaved in ASCII. WordStar users must open batch files in theNon-Document mode. Microsoft Word users can create batchfiles, then save them in ASCII format by choosing the "No"option in the "Transfer Save" menu. Check the user's manualfor your word processor for its procedures.

If you're not sure about the method your editor uses, trycreating a batch file. Save it, then exit the program anduse the TYPE command to display the file on your monitor.If you see your file, without any extra characters on thescreen, you know that it is pure ASCII, and can be used as abatch file.

Page 4

Whichever method you use, remember to use the .BAT extensionand don't give your file a name which would conflict withanother executable file in its directory. If your batchfile has a name which is the same as a .COM or .EXE file, ora DOS internal command, it simply won't execute.

A SPECIAL BATCH FILE: AUTOEXEC.BAT

When you boot up your computer, several things happen.First, the ROM BIOS in your PC checks the system's memory,then looks for a disk in drive A: or for a hard disk drive.It then loads the system files from the disk into memory.These files include COMMAND.COM plus two hidden files. Onethese files are loaded, it looks for a file calledCONFIG.SYS and carries out any functions contained in thatfile.

Finally, it looks for a batch file named AUTOEXEC.BAT. Ifthe file exists, PC/MS-DOS carries out the commands in thatfile. If there is no AUTOEXEC.BAT file, you see thestandard request for the current date and time on yourscreen.

An AUTOEXEC.BAT file can contain any commands you want touse every time you boot your PC. Suppose, for example thatyou always wanted to start the program, Microsoft Word, when

3

Page 4: Batch.files.explained

batch_files_explained.txt 26/02/2002

you turned on your PC. Just create a batch file, namedAUTOEXEC.BAT on your boot disk, or in the root directory ofyour hard disk, using one of the techniques above. Thisfile has only one line:

WORD

Naturally, you could substitute the command you use to startany program you choose. When PC/MS-DOS finds anAUTOEXEC.BAT file, it bypasses the date and time sequenceand immediately carries out the command in the file.

Now, suppose you need to change directories on your harddisk before starting the program. Using Word as an exampleagain, here's a sample file:

CD WPWORD

This time, the AUTOEXEC.BAT file tells the PC to change tothe \WP directory, then start Microsoft Word. It's easy tosee how you could adapt this to your own needs.

Now, let's add something else. Many users install memory-resident programs before loading an application. SideKickis a popular memory resident program. Here's a sample file:

Page 5

CD UTILITYSKCD \WPWORD

Line-by-line, here's what this AUTOEXEC.BAT file does:

1. Changes to the \UTILITY directory on your hard disk.2. Loads SideKick.3. Changes to the \WP directory.4. Loads Microsoft Word.

Once again, you can substitute any directory name or commandfor the ones used in this sample file. Try creating yourown AUTOEXEC.BAT file, using commands you select.

OTHER SIMPLE BATCH FILES

Batch files can be extremely useful in saving keystrokes. Ioften create them just to avoid typing long filenames orcommands. Let's look at some ways to help yourself out withbatch files.

When you looked at the section on AUTOEXEC.BAT files, youlearned how to start a program automatically when you bootedyour system. You can use other batch files to startprograms with just a keystroke or two. Let's keep usingMicrosoft Word as an example.

As before, I'll assume that we're working with a hard disk.Floppy disk users can just leave out the directory changecommands in their batch files. Here's a simple batch file,named W.BAT that starts the program with a single keystroke.

4

Page 5: Batch.files.explained

batch_files_explained.txt 26/02/2002

CD WPWORD

Now, when you use this file by typing a <W> and pressing<Enter>, Microsoft Word will run. When you exit from theprogram, however, you'll still be in the \WP directory onyour hard disk. Add a third line to return you to the rootdirectory when you exit Word. W.BAT will look like this:

CD WPWORDCD\

When you leave Word, PC/MS-DOS knows that the batch filestill has another command, so it returns to it and carriesout the next command in the file.

Suppose that you normally move to another program afterexiting Word. You can have your batch file do this

Page 6

automatically. Let's try starting Lotus 123 after exitingWord. Here's a batch file to do just that:

CD WPWORDCD \LOTUS123CD\

You can easily see how many keystrokes are saved by using abatch file instead of typing in all the commands. Andthat's just the beginning.

Batch files are actually simple computer programs. Bywriting these files, you are learning simple computerprogramming.

In this first part of the series, you've learned how tocreate simple batch files which save keystrokes. But batchfiles can do much more. Using the full power of PC/MS-DOSbatch files, you can actually create real programs.

In future parts of this series, you will learn how to createmenus to help you or others run a PC. You will also learnhow you can dial your phone using batch files, createsoftware installation programs, control your printer, andperform many other operations with a single keystroke.

More than that, batch files can create systems to protectyour PC and its files from prying eyes and fingers. You caneven create a database system with batch files which willlet you have almost instant access to any information.

Batch files can use a number of special commands to teachyour PC to do things you never thought possible. Best ofall, they are easy to use.

Part 2: Batch File Menus

5

Page 6: Batch.files.explained

batch_files_explained.txt 26/02/2002

Whether you use a hard disk or floppies on your PC, learningto create a menu system can save valuable minutes and makeyour PC easier to use. In addition, if you help otherpeople with their computers, installing a menu system canhelp you avoid constant phone calls for help.

Batch files are an ideal method for creating menus. Batchfile menu systems are easy to write, easy to change, andextremely powerful. You can incorporate as many featuresinto your menu as you like, allowing you or anyone else toaccess programs with a single keystroke.

USING THE ECHO COMMAND

Page 7

To create a menu system, you need to be able to writeinformation on the screen with your batch file. PC/MS DOSgives you a command which makes this easy: ECHO. Here's howit works:

You can use the ECHO command in two ways. Each uses adifferent format. The first format allows you to tell yourPC whether or not you want to see the commands in your batchfile listed on the screen. Usually you don't, and thecommand used to disable screen writing is: ECHO OFF

When you include this command in a batch file, commands inthat file will not appear as they are executed. This makesfor a cleaner screen appearance. To turn the ECHO functionback on, just include the command: ECHO ON.

The second format for the ECHO command allows you to placemessages on the screen. You'll use this function to writeyour menu on the monitor. The syntax is: ECHO [message]

For example, to write the line "Master Menu" on the screen,include the command: ECHO Master Menu as a line in yourbatch file. You can control the position of the message byincluding spaces. If you want to center a line on thescreen, simply subtract the number of characters in yourmessage from 80, then divide the result in half. Place thatnumber of spaces in front of your message.

To make a menu or other text screen attractive, you need tobe able to add blank lines. The ECHO command can do this aswell, but there's a trick to it.

Until DOS Version 3.3 appeared, creating blank lines wasn'tsimple. Instead of simply following the ECHO command with aspace, which creates a blank line in DOS 3.3, earlierversions of DOS require a special method. This method willwork with any version of DOS from 2.0 to 3.3.

To create a blank line, place the ECHO command on a line inyour batch file. Next press the space bar once, then holddown the <Alt> key while you type 255 on the number pad.The numbers at the top of the keyboard won't work. Doingthis inserts the ASCII character number 255, which is ablank character. This fools DOS into thinking that there isa message, and creates a blank line on the screen.

6

Page 7: Batch.files.explained

batch_files_explained.txt 26/02/2002

This method works with the COPY CON method for creatingbatch files, and with most word processors. If your texteditor doesn't support this function, either use anothereditor or simulate a blank line by inserting a periodfollowing the ECHO command.

One final note on the ECHO command: You cannot use the DOSredirection characters (< and >) in an ECHO statement. If

Page 8

you do, the error message, "Bad command or filename," willappear.

CREATING THE MENU SYSTEM

Now that you know how to use the ECHO command to createmessages on the screen, you're ready to create a menu. Forthe purposes of this article, let's assume that you wantyour menu to call Microsoft Word, Lotus 123, QMODEM, and thegame ROGUE. You can also include a menu choice to return toDOS in the menu. Naturally, you will use the programs onyour disk as replacements for those in this sample program.

Using the COPY CON command as described in the first part ofthis series, or your favorite text editor, create the fileMENU.BAT in the root directory of your hard disk or on afloppy disk. Don't include the comments in parentheses, andsubstitute names of programs.

ECHO OFF (Turns off the echoing of batch file commands)CLS (Clears the screen)ECHO [Alt-255] (Create a blank line as described above. Useas many of these blank lines as you like.)ECHO[35 spaces]Master MenuECHO [Alt-255]ECHO[32 spaces]Do you want to:ECHO [Alt-255]ECHO[15 spaces]1. Use your word processor?ECHO[15 spaces]2. Use Lotus 123?ECHO[15 spaces]3. Use your communications program?ECHO[15 spaces]4. Play Rogue?ECHO[15 spaces]5. Return to the DOS prompt?ECHO [Alt-255]ECHO At the DOS prompt, type the number of your selectionECHO and press [Enter].

Be sure to place a carriage return at the end of the lastline of the file, then save it in ASCII format, or press<F6> if you are use the COPY CON command. To call your menuscreen when you boot your computer, include the command,MENU, as the last line of your AUTOEXEC.BAT file.

Once again, you can customize this menu screen any way youlike. Include as many menu choices as you need, and insertblank lines and spaces to make the screen as attractive aspossible.

When MENU.BAT is executed, it will write the menu on themonitor, then the system prompt will reappear.

7

Page 8: Batch.files.explained

batch_files_explained.txt 26/02/2002

EXECUTING YOUR MENU CHOICES

Page 9

Once you've written the MENU.BAT file, you need to writeindividual batch files for each menu choice. These fileswill call a program when you or the user enters a menuselection.

Name the files to match your menu selections. In the samplemenu presented here, the files would be named 1.BAT, 2.BAT,and so on. Each of these files will contain the commandsneeded to call the program. Here's 1.BAT:

ECHO OFF (This line turns off the ECHO function)CLS (Clear the screen)CD WP (Change directories...not needed for floppies)WORD (Call Microsoft Word)CD\ (Change to the root directory after quitting Word)MENU (Return to the menu)

Naturally, you'll include the commands needed to perform thefunctions in your menu, rather than the ones used here.Floppy disk users can ignore the CD commands in their batchfiles.

Create a separate file for each menu choice. The last menuchoice, which you should include in any menu system, takesthe user to the DOS prompt, allowing him or her to use thecomputer for purposes not included in the menu. Here's asample, 5.BAT, for this menu:

ECHO OFFCLSCD\

This file will return the user to a clean screen and thesystem prompt.

REFINING YOUR MENU SYSTEM

Generating screens with the ECHO command is only one of theways you can write information on the monitor. If youcreate a complex screen, you'll notice that when the batchfile executes, the screen appears rather slowly. This isone of the drawbacks to the ECHO command.

There's an alternative to the ECHO command for screengeneration. Since you can use any DOS command in your batchfiles, you can use the TYPE command to place text on thescreen.

To do this, create your screen with your text editor or wordprocessor. Save the screen as an ASCII file, then call itwith the TYPE command in your MENU.BAT file. The menu willappear much faster, particularly if it is a complex one.You can even include boxes and other special characters ifyour text editor supports extended ASCII characters.

8

Page 9: Batch.files.explained

batch_files_explained.txt 26/02/2002

Page 10

Keep your text screens shorter than 23 lines to preventunwanted scrolling when the TYPE command lists the file onthe monitor.

Here is a MENU.BAT file which performs the same function asthe previous one, but this time it calls a screen createdwith a word processor. The screen file is named MENU.DOC.

ECHO OFFCLSTYPE MENU.DOC

This file is obviously much shorter, and the menu screenwill appear very quickly on the monitor. The individualfiles which call the programs will be exactly the same.

In many cases, you may want to eliminate the DOS promptentirely from your menu. That's easy, using the PROMPTcommand. PC/MS-DOS allows you to customize a prompt to suityour needs. As an example, you could replace the last twolines in the original MENU.BAT file shown above with thefollowing line:

PROMPT Type your selection and press [Enter]:

This line would replace the normal A> or C> prompt with thetext following the PROMPT command. The normal cursorappears at the end of the new prompt.

You can even eliminate the prompt completely. Do this byusing the same <Alt>-255 keystroke combination used with theECHO command. Just type PROMPT, then hold down the <Alt>key while you type 255 on the number pad.

If you turn off or change the prompt, however, be sure torestore it to its original form in the menu selection filewhich returns the user to DOS. To do this, simply add aline to the batch file. This line should contain thecommand, PROMPT, and nothing else, and will restore thenormal system prompt.

MULTI-USER MENUS

The menu-creation process can be further refined forcomputers used by more than one person. In many cases, youwant to restrict certain users to a specific group ofprograms. This technique can even be used to create asimple password system. It's not extremely secure, but willlimit unsophisticated users to a limited group of programs.Here's how to create this type of system.

First, create a batch file called PASSWORD.BAT. Here's asample:

9

Page 10: Batch.files.explained

batch_files_explained.txt 26/02/2002

Page 11

ECHO OFFCLSPROMPT Please enter your password:

Call this file from the AUTOEXEC.BAT file, after loading anymemory-resident programs, and performing any other start-upfunctions. The screen will clear, and the prompt will askfor the user's password. If security isn't important, youcould ask for the user's name instead.

Now, create a menu for each user, giving it a filename whichmatches the password or name the user will enter. Using thetechniques described above, you can limit access to aspecific list of programs for each user. In this case,however, don't include a menu choice which exits to DOS.Instead, make the last menu choice call the PASSWORD.BATfile. If you need to change a user's password, simplychange the name of the batch file which calls that user'smenu.

If the user needs to use certain DOS commands, such as COPY,DELETE, or BACKUP, you can allow the use of a limited set ofDOS commands by including them in a directory, then changingto that directory with a batch file called from the user'smenu.

Once again, this system is not perfectly secure. Any usersophisticated enough to use the <Ctrl>+<Break> combinationcan exit to DOS. When he or she does that, however, theprompt will still ask for a password.

If you use DOS 3.0 or a later version, you can add to thesystem's security. Use any utility program, such as NortonUtilities or PC-Tools to change your password batch files tohidden files. Anyone doing a directory will not see thefiles on the screen, but DOS knows they are there and willexecute them normally. Earlier versions of DOS cannotexecute hidden files.

As the installer or main user of a multi-user PC, you canbypass the password system by having a batch file with yourpassword simply reset the prompt and exit to DOS. This willallow you or another user full access to the system.

The next part of this series will introduce a number ofother DOS commands which are especially useful in batchoperations. Using these commands, you will gain even morecontrol over your PC and its peripherals, increasing thepower of your batch files.

Page 12

Part 3: Expanding Batch File Operations

10

Page 11: Batch.files.explained

batch_files_explained.txt 26/02/2002

If you're like most PC/MS-DOS users, you use a few basic DOScommands regularly. Other commands you may not use,however, have the power to make your PC even more useful andefficient.

Including these commands in your batch files can add newflexibility and let you control your PC better, making it aneven more powerful tool. Here are some little-known DOScommands especially suited for batch files.

The ASSIGN Command

This very powerful DOS command tells your PC to send allcalls for one disk drive to another. Programs often lookfor data on a specific drive. This is especially true withpublic domain and shareware programs.

These programs assume that the disk containing data files isin drive A: or B:. Hard disk users often have difficultiesrunning these programs. When the program wants to open afile on drive A: and that file is on drive C:, the programcan't find the file and often just exits to DOS.

Using ASSIGN, you can tell your PC to look on drive C: forfiles, no matter what the program tells it to do. Here'sthe format for that command:

ASSIGN [D1 = D2]

To send all calls for drive A: to drive C:, the commandwould be:

ASSIGN A = C

There are a few restrictions to the use of ASSIGN. Youcan't use it while using the PRINT command. In addition,FORMAT will not run when ASSIGN is in use. Notice, too,that colons aren't used after the drive names when you usethe ASSIGN command.

After using this command, you must turn off the driveassignment before going on to other computer operations.Simply issue the command, ASSIGN, without any driveparameters. You can do this automatically in a batch file.

For an example, let's assume you want to run the gameprogram, CASTLE, which looks for a data file in drive A:.You have CASTLE and its data file on Drive C:, which wouldabort the program when it couldn't find the data file.Here's a batch file to solve the problem:

Page 13

ASSIGN A = CCASTLEASSIGN

This file, which you might call PLAY.BAT, solves theproblem, and returns you to the normal configuration whenyou exit from the game.

You can also use the ASSIGN command to lock out your hard

11

Page 12: Batch.files.explained

batch_files_explained.txt 26/02/2002

disk if you are testing a questionable program. Just givethe command, ASSIGN C = A, and the PC won't try to write anydata to your hard disk. Just remember to get rid of theassignment before resuming normal operations.

The ECHO Command

In part 1 of this series, you learned to use this command todisplay screen messages. ECHO can perform other functions,however, which are useful in batch files.

For example, you might want to make the computer beep atsome point during the execution of a batch file. To dothis, include the following command as a line in your file:

ECHO ^G

Type ECHO, press the space bar once, then hold down the<Ctrl> key while you press the <G> key. This adds acharacter, ASCII number 7, to your command. Whenever thiscommand executes, you hear the familiar beep.

You can also use the ECHO command with the DOS redirectioncharacters < and > to send text to your printer or to yourserial ports.

Here's a good example: You may need to print labels withyour return address on them. It's easy, using a batch filecontaining the following lines:

ECHO Your Name >PRNECHO 123 Your Street >PRNECHO Anytown, Anystate 12345 >PRN

Add blank lines before and after the text. Adjust thenumber of blank lines to suit your printer and the labelsyou use. You'll have to experiment to get it just right.

Call this batch file RETURN.BAT, or any other name you like.Whenever you execute the file, it will print your returnaddress, saving you from starting your word processor tocreate an address label. You can also create similar filesfor other addresses.

The MODE Command

Page 14

The MODE command allows you to control your monitor, yourserial ports, and your printer. The command is very seldomused, due to its hard-to-remember syntax. This makes it anatural for batch files.

To use the MODE command in batch files, the DOS utilityMODE.COM or MODE.EXE must be in your current PATH, or on thefloppy disk containing your batch file. If DOS can't findthe program, an error message will appear on your monitor.

If your PC has a CGA or EGA display adapter, you can use theMODE command to change from one display mode to another. Ifyou want to change from the normal mode to a forty-charactercolor screen, include the following line in a batch file:

12

Page 13: Batch.files.explained

batch_files_explained.txt 26/02/2002

MODE CO40

Check your DOS manual for other screen modes. You caninclude this command in a long batch file, or use it alonein a file called 40.BAT.

The syntax for the MODE command format used to set up yourserial port is very complex. Using a batch file, you canavoid having to memorize this syntax. To set your COM1:port to 1200 baud, with even parity, seven data bits, andone stop bit, just use the following line in any batch file:

MODE COM1: 1200,E,7,1

Later, you will learn how to incorporate this command linein a batch file telephone dialing system.

Many users have a printer connected to a serial port. Inthis case, DOS needs to know where the printer is, since itassumes that the printer is connected to LPT1:. Include thefollowing line in your AUTOEXEC.BAT file and your PC willautomatically send all printer output to COM1:.

MODE LPT1: = COM1:

If your printer, on the other hand, is connected to LPT2:,the second parallel port, use the following line:

MODE LPT1: = LPT2:

Finally, you can use the MODE command to set your printer'smode of operations, controlling the number of characters perline, the number of lines per inch, and whether or not youwant the computer to keep trying if the printer sends anerror message to the computer. Here's the syntax:

MODE LPT#: [characters\line], [lines/inch], [P]

Page 15

Following this syntax, to set your printer for 80 charactersper line, 8 lines per inch, and to retry on errors, use thefollowing command in a batch file:

MODE LPT1: 80,8,P

The PAUSE Command

Many time, during the execution of a batch file, it isuseful to have the batch file stop operations while you dosomething, like load paper into the printer. The PAUSEcommand halts the operation of a batch file temporarily.

Like many other batch file commands, PAUSE allows you toinclude a message. As an example, you can create a batchfile which tells the user to put a blank, formatted disk indrive B: before a COPY operation. Here is the command touse:

PAUSE Place a blank, formatted disk in drive B:

13

Page 14: Batch.files.explained

batch_files_explained.txt 26/02/2002

When DOS encounters this line in a batch file, it displaysthe following information on the screen:

Place a blank, formatted disk in drive B:Strike a key when ready...

The batch file stops until the user presses any key. When akey is pressed, the batch file moves to the next line andexecutes the command there. The command might be to COPY afile or files to the disk the user inserted in drive B:, asrequested by the PAUSE message.

The PROMPT Command

In the previous part of this series, you learned to use thePROMPT command to replace the standard DOS system promptwith a message. This command can also be use to createother customized prompts. Including one of these PROMPTcommands can add productivity to your work.

This format of the PROMPT command uses the <$> character incombination with a letter to change your normal prompt.Here's an example:

PROMPT $n$g

This sets the prompt to the normal A> or C>, depending onthe default drive you've set. If you'd rather see a promptwhich displays the current directory, include this variationin your AUTOEXEC.BAT file:

PROMPT $p$g

Page 16

There are a number of other characters, which set theprompt. You can use them in any combination you choose,preceding each letter with a dollar sign.

Character Display

$t The current time$d The current date$p The current directory$v The DOS version number$n The current drive$g The ">" character$l The "<" character$b The "|" character$_ (underscore) A carriage return

Using a combination of these character commands, along withtext, you can create customized prompts. Just for anexample, let's look at a complex PROMPT command:

PROMPT Hello, Mary$_It's $t$_You're in the $pdirectory$_Please enter a DOS command $g

PROMPT commands must be entered on a single line, so don'tinclude any carriage returns. When this PROMPT is includedin a batch file it will produce a prompt which looks like

14

Page 15: Batch.files.explained

batch_files_explained.txt 26/02/2002

this on the monitor:

Hello, MaryIt's 9:25:32.21 (current time)You're in the \UTILITY directory (actual directory)Please enter a DOS command >

Experiment with this command to create custom prompts foryourself, or to provide information to other PC users.Including a special PROMPT command in your batch files canincrease your productivity and prevent confusion.

The REM Command

Working with batch files is actually a form of programming.As your batch files grow in length, they can becomeconfusing. Inserting comments can help you understand howthe file works. This is especially important when you needto change a complex batch file later.

The REM command allows you to insert comments in your files.Any text in a batch file which follows a REM command cancontain your comments. These comments will not be seen onthe monitor, but will appear when you TYPE the file or printit out. I recommend using REM comments frequently in longand complex batch files you create.

Page 17

Here's an example:

REM This batch file copies three files to Drive B:PAUSE Insert a blank, formatted disk in Drive B:COPY LETTER.DOC B:COPY RESUME.DOC B:COPY NOVEL.DOC B:REM The next line displays LETTER.DOC on the monitor.TYPE LETTER.DOC

Using the DOS Redirection Characters

Earlier in this series, the two DOS redirection characters,< and > were mentioned. These characters are a powerful wayto tell your PC to send the output of files to a differentplace than they would normally go. Using redirection inyour batch files can be a powerful tool.

For example, you might want to print a text file from withina batch file. Using the TYPE command and a redirectioncharacter, it's easy. Here's a command which you can use tosend any text file to a printer:

TYPE [filename.ext] >PRN

The ">" character redirects the output of the TYPE commandfrom the monitor to the printer. You will use thisfrequently.

Similarly, to send a directory to the printer, include thefollowing command in any batch file:

DIR >PRN

15

Page 16: Batch.files.explained

batch_files_explained.txt 26/02/2002

It's easy to see how useful this can be. When you redirectthe output from a command to another device, such as theprinter, it doesn't appear in its usual place. You can usethe redirection character to send output to the followingdevices:

PRN (a printer attached to LPT1:)LPT#: (A parallel port)COM#: (A serial port)CON (The monitor)NUL (Nowhere at all)

The last device, NUL, is your computer's version of Never-Never-Land. Anything sent to the NUL device simply goesnowhere at all. Oddly enough, this is very useful in batchfiles.

Many DOS commands you will use in batch files producemessages on the screen. The COPY command is a good example.Whenever you COPY a file or files, the familiar message, "#

Page 18

file(s) copied," appears on the screen when the operation isfinished.

There are many times when you don't want that message toshow, especially when your batch file copies multiple files.Having the message appear slows down the operation, andclutters the screen you have so carefully created. Here'san example of the use of the NUL device:

COPY LETTER.DOC B: >NUL

Including the redirection character and the NUL device tellsDOS to send the message, "1 file(s) copied," to the NULdevice instead of to the monitor. It's very simple.

Other uses for this function include getting rid of messagesprovided by many memory-resident programs. If you don'twant to see the message, simply redirect it to the NULdevice in the line used to call the program.

You can even use this technique to introduce delays intoyour batch files. Simply COPY a file to the NUL device. Thelonger the file, the longer the delay. Here's an example:

COPY LETTER.DOC NUL >NUL

When DOS encounters this command, it reads the file, thencopies it right into oblivion. The original file remains onthe disk, but the time it takes to read the file will simplycause a delay in the execution of the batch file. Thesecond NUL combined with the redirection character keeps theCOPY command message off the screen.

Command Line Parameters

Since a batch file can contain commands which execute otherbatch files, it is useful to be able to include variables inyour batch files. DOS allows you to do this with aparameter you include when you execute the original file.

16

Page 17: Batch.files.explained

batch_files_explained.txt 26/02/2002

By typing the name of the batch file, a space, then theparameter, you can tell DOS that you have included avariable in your command. You have used this feature beforewith commands like: FORMAT B: or CHKDSK A:. The drivedesignator in each of those commands is a replaceableparameter which you can change each time you give thecommand.

These parameters, when used with batch files can representanything you wish, a drive name, a file, or the commandwhich starts another batch file.

The replaceable parameter is represented in the batch fileitself with a per cent sign (%), followed by a number

Page 19

between 1 and 9. Whenever your file encounters this sign itsubstitutes your command line parameter for the sign.

For example, to create a batch file which copies all filesfrom either drive A: or drive B: to your hard disk, which isdrive C:, using a simple command, use C.BAT below:

ECHO OFFCLSCOPY %1:*.* C:

To use this batch file, give the following command:

C AorC B

With three keystrokes, you can save typing in the entirecommand sequence. Notice that the parameter is expressed inthe batch file with a number (%1). You can use up to ninecommand line parameters (%1 to %9), separated by spaces inyour batch files. This opens up many possibilities.

You can expand the C.BAT file above to accept a pathparameter as well. This lets you specify a directory onyour hard disk, allowing you to copy the files to a specificdirectory. Here's the new C.BAT:

ECHO OFFCLSCOPY %1:*.* C:\%2

Now, give this command:

C A TEMP

This time, your batch file copies all files from drive A:,the first parameter, to the \TEMP directory on drive C:.Each time you execute the batch file, you can use differentparameters to control the process. Here's the command thisbatch file has replaced:

COPY A:*.* C:\TEMP

It's easy to see how many ways you can use command line

17

Page 18: Batch.files.explained

batch_files_explained.txt 26/02/2002

parameters to control functions in batch files.

A Batch File Telephone Dialing System

Now that you've learned some of the DOS commands which areespecially useful in batch files, it's time to use some ofthese commands for a practical application. Since most ofus call a small list of people regularly while we're using

Page 20

the computer, creating a batch file dialing system makessense.

This system requires a Hayes-compatible modem, and can dialan unlimited number of people, depending only on how manyfiles you want to create.

First, create a directory called \PHONE in the rootdirectory of your hard disk. Include this new directory inyour PATH so you can access it from any other directory. Ifyou use a floppy-based PC, format a floppy disk to hold yourdialing system.

Now, using either the COPY CON command or your favorite texteditor, create the following batch file, naming it CALL.BAT:

ECHO OFFCLSCD\PHONE REM Leave this line out for floppy systems.ECHO Calling %1......MODE COM1:1200,E,7,1 >NUL%1CD\ REM Leave this line out for floppy systems

If you have a 300 or 2400 baud modem, simply substitute thatnumber in the fourth line of the file. Notice that linefour uses the >NUL redirection routine to eliminate thescreen message produced by the MODE command.

Now, create a separate batch file for each person you wantto include in your dialing system. Name the files so theywill be easy to remember, and give each file the .BATextension. For example, you might create BILL.BAT, MOM.BAT,DOCTOR.BAT, or any other filename you might use. Justremember that the filename must be no more than eightcharacters long.

Here's a sample file, named BILL.BAT

ECHO OFFCLSECHO ATDT5551234 >COM1:

Naturally, you would substitute the correct phone number forthe person you're calling. If you are in a non-tone dialingarea, substitute ATDP for ATDT to use pulse dialing.Finally, if your modem is connected to another COM port, usethat port designator in place of COM1:. Create as manyfiles as you like, storing them all in the \PHONE directoryor on your floppy disk.

18

Page 19: Batch.files.explained

batch_files_explained.txt 26/02/2002

If your modem uses a different dialing command than theHayes-compatible ATD? command, make another substitution inthe ECHO line.

Page 21

Here's how the system works: To call Bill, or another personin your system, give the command, CALL BILL, and press<Enter>. The first batch file, CALL.BAT, clears the screen,tells you who you are calling, then sets the communicationsparameters with the MODE command. Next, it executes thebatch file with the name you used as a replaceableparameter, Bill in this case.

BILL.BAT executes, using the ECHO command to send thedialing command and the telephone number to your modem. Atthis point, you can listen to the progress of the call onyour modem's speaker, or just pick up the phone and wait foran answer.

You can use your dialing system anytime you see the systemprompt. Many programs allow you to exit temporarily to DOS,so you can also make phone calls while using any of theseprograms.

You can use DOS batch files as a simple programming languageto create programs like the dialing utility above. Theadvantage to batch programming is its simplicity. Creatinga telephone dialing system in most other programminglanguages would take hours. Using batch files, the programis finished in minutes.

A Batch File Database

Following a similar format to the telephone dialing system,you can create a simple database system to store names andaddresses, using simple batch files. First, create a newdirectory called \FILE on your hard disk or format a floppydisk to be used for this system. One again, if you installthis system on your hard disk, be sure to include it in yourPATH for easy access.

Write the following batch file, LOOKUP.BAT, to serve as themain program:

ECHO OFFCLSCD\FILE REM You can leave this line out for floppy systems.ECHO Searching.......TYPE %1.ADD REM This command line parameters displays the fileCD\ REM Again, leave this line out for floppy systems.

When creating this file, leave off the REM commands and thetext following them.

Now, for each person you want to include in your database,create a plain ASCII file which looks like this:

ANYNAME DOE

19

Page 20: Batch.files.explained

batch_files_explained.txt 26/02/2002

Page 22

1235 SOME STREETANYTOWN, STATE ZIP(555) 555-5555<Enter> REM These lines add blank lines. Use as many<Enter> REM as you need.

Give the file a distinctive name you'll remember. Use theextension, ADD. Store the file in the same directory or onthe same disk as LOOKUP.BAT. Now, to view the informationon your monitor, just enter the command:

LOOKUP NAME

Your LOOKUP.BAT file will find the filename you specify onthe command line and display the information. Of course,you might not remember just which file you want to check.It's easy to write another batch file which will show you alist of files. You might call this one FINDFILE.BAT:

ECHO OFFCLSCD\FILE REM Not used in floppy systems.DIR *.ADD/WCD\ REM Not used in floppy systems.

By entering the FINDFILE command you will see a display ofyour filenames for this system. Notice the fourth line ofthe batch file. It reads DIR *.ADD/W. The *.ADD sectiontells DOS to show only those files which have the extensionyou use for your data files. This helps keep extraneousinformation off the screen.

Now, suppose you want to print one of your files. Here'sanother batch file to do that. Let's call this onePRINTIT.BAT.

ECHO OFFCLSCD\FILE REM Not used in floppy systems.COPY %1.ADD PRNCD\ REM Not used in floppy systems.

All you have to do is enter a command like this one:

PRINTIT NAME

The file you name on the command line will go directly toyour printer. If you have included the right number ofblank lines in your original files, you can use thisPRINTIT.BAT to print address labels. You'll have toexperiment to get your files just right for your particularprinter and labels.

20

Page 21: Batch.files.explained

batch_files_explained.txt 26/02/2002

Page 23

Finally, you can write one more batch file which will printyour entire list of files, creating mailing labels if youhave formatted the files properly. Call this onePRINTALL.BAT.

ECHO OFFCLSCD\FILE REM Not used in floppy systems.COPY *.ADD PRN >NULCD\ REM Not used in floppy systems.

Enter the command, PRINTALL, and every one of your fileswill be printed automatically.

This address system is only one way you can use your batchfile database. Another possibility is a recipe database.By storing files containing your recipes, you can use thesame batch files to call up your favorites, print them out,or even print the entire recipe database.

Just remember that any files you store in your batch filedatabase must be pure ASCII files, created with either theCOPY CON command or your favorite word processor or texteditor. If you use a word processor, be sure to save thefiles in ASCII format.

The possibilities for different kinds of data storage areendless. You also have the advantage of not being restrictedto defined fields and field sizes, as you do with a regulardatabase.

In the next part of this series, you will learn severaladvanced batch file techniques, including ways you can usebatch files in your programming. That part will also coverthe creation of a batch file system to control your printer.It will allow you to change your printer's output with asingle command.

Part 4: Advanced Batch File Techniques

The first two parts of this series on batch files introduceda number of techniques to help you automate many of theoperations you perform frequently on your PC. This time,we're going to take a look at more advanced batch filefunctions, adding even more power to your batch processing.

Like all programming languages, batch files can performloops and conditional branching. Loops allow your batchprogram to perform the same function several times, usinginformation you supply to control the process. Conditional

Page 24

branching lets your batch files test to see if a conditionis true and, if it is, forces the batch file to execute asubroutine. Let's look at conditional branching first.

21

Page 22: Batch.files.explained

batch_files_explained.txt 26/02/2002

BATCH FILE IF....GOTO BRANCHING

If you are familiar with any programming languages, such asBASIC, the IF....GOTO sequence is familiar to you. The IFpart of the sequence lets you test something, while the GOTOcommand tells your program to skip to a subroutine and carryout the commands it finds there. This capability is centralto all programming, including batch programming.

Before looking at the IF command, it's important tounderstand how the GOTO command works. Unlike manylanguages, DOS batch programs use labels with the GOTOcommand. A label marks the beginning of the subroutine,letting DOS know where to begin processing after itencounters a GOTO line.

Batch file labels always begin with a colon (:). The labelfollows the colon, without any spaces or other characters.Here are some examples of correct label format:

:START:ABORT:QUIT

A label should be placed on a line by itself, immediatelypreceding the first command in the subroutine. This samplebatch file, called SAMPLE.BAT, will demonstrate the use ofthe GOTO command:

ECHO OFFCLSECHO This batch file demonstrates branching.GOTO ROUTINE1ECHO The batch file will skip this line.ECHO It will skip this line as well.:ROUTINE1CLSECHO You are now in the first sub-routine.ECHO When you press a key, you will go to the nextroutine.PAUSEGOTO ROUTINE2ECHO Again, the batch file will skip this line.ECHO And this one, too.:ROUTINE2CLSECHO Now you are in the second sub-routine.ECHO Notice that the file skipped several lines.

Page 25

ECHO Pressing a key will take you to the thirdroutine.PAUSEGOTO ROUTINE3ECHO Another line skipped.ECHO Still another skipped line.:ROUTINE3CLSECHO Now you have reached the third subroutine.

22

Page 23: Batch.files.explained

batch_files_explained.txt 26/02/2002

ECHO This is the last subroutine.ECHO When you press a key, you will exit to DOS.PAUSECLS

Create this simple batch file, using the COPY CON command oryour favorite text editor. Remember to save the file inASCII format. Once you have created the file, run it. Youwill notice that the lines between the GOTO commands and thelabels do not execute. Once DOS encounters the GOTO, itimmediately jumps to the label, skipping all intermediatelines.

When creating a label, use from one to eight characters.Avoid punctuation, and always use labels which aremeaningful, to help you understand your batch file later.Unlike other languages, DOS allows you to use reservedwords, like COPY and DELETE as labels in your batch files.For clarity's sake, however, it's best to avoid labels whichare also the names of DOS commands.

CONDITIONAL BRANCHING WITH THE IF COMMAND

By itself, the GOTO command has limited usefulness. There isusually no reason to use GOTO unless you are testing to seeif a condition is true or not. That's where the IF commandcomes in.

Most programming languages use a command similar to the DOSIF command to test for a wide variety of conditions. Inbatch files, you are limited to testing just a few things:

1. Whether one string of characters equals another.2. Whether or not a file exists.3. The ERRORLEVEL of a program.

In this article, we'll look at the first two conditions.The third is of limited usefulness to most DOS users.

The first condition which can be tested with the IF command,whether one string is equal to another, is the most common.If you remember the discussion on command-line parameters,you know that a batch file can use up to 10 parameters whenyou give the command to execute the batch file. An exampleof this might be the command, FORMAT A:. The A: part of

Page 26

this command is a replaceable parameter, used by DOS toidentify the drive to be formatted.

By using the IF command in your batch files, you can checkto see whether a command-line parameter equals a string youhave specified in the batch file. Here's an example, whichwe'll call TEST1.BAT:

ECHO OFFCLSIF %1. == . GOTO WRONGIF %1 == HELLO GOTO CORRECTGOTO END:CORRECT

23

Page 24: Batch.files.explained

batch_files_explained.txt 26/02/2002

CLSECHO You typed HELLO.ECHO The batch file branched to the CORRECT routine.PAUSEGOTO END:WRONGCLSECHO You didn't include a parameter in your command.ECHO To get to the subroutine, type the command:ECHO TEST1 HELLO, then press [Enter].PAUSEGOTO END:ENDECHO You typed something other than HELLO as aparameter.ECHO DOS recognizes the difference between upper andlower case.ECHO Try again.PAUSECLS

Let's take a look at some of the lines in this file. Thefirst two lines are familiar, turning off ECHO and clearingthe screen. The next line is new and uses the IF command.

When you use the IF command to check command-line parametersand no parameter is given when the batch file is called, DOSnormally returns the error message: SYNTAX ERROR. The linein TEST1.BAT which reads: IF %1. == . GOTO WRONG GOTO ENDtests to see if no parameter was given. The period (.) isused to supply a single character following the %1parameter. Without it, the error message INVALID NUMBER OFPARAMETERS would appear. This line branches to the :WRONGsubroutine if no parameter was used on the command line.

The next line checks to see if the command-line parameterwas HELLO. If it was, the batch file branches to theroutine named :CORRECT.

Page 27

Following the second IF line is a line which reads, GOTOEND. This line comes into play if neither of the conditionsin the previous lines is true. If, for example, thecommand-line parameter was GOODBYE, the batch file wouldbranch to the :END routine, skipping the rest of the file.

It's important to include a line which branches around otherlines if a condition isn't true. Otherwise, the batch filewould simply go right into the :CORRECT subroutine.

The IF command recognizes upper and lower case letters asdifferent. So, typing hello in lower case letters would notsatisfy the condition in the second IF line.

Finally, notice that each subroutine in this batch fileincludes a GOTO END line. Again, this forces the program tobranch around succeeding subroutines, avoiding errors.

Create this batch file, then run it. The first time, do notinclude the parameter HELLO on the command line. Next, addhello to the command, using lower-case letters. Finally,

24

Page 25: Batch.files.explained

batch_files_explained.txt 26/02/2002

include the correct form of the parameter, HELLO. You willsee the messages in the appropriate subroutine. Be sure touse two equal signs (==) in your IF lines. This iscritical.

Creating a Practical Application Using Branching

While the sample batch file above demonstrates the use ofthe IF and GOTO commands, it doesn't serve any usefulfunction. Let's create a batch file which solves a seriousproblem.

It's all too easy to accidentally format a hard disk,particularly with versions of DOS earlier than 3.0. Bysimply typing the command FORMAT and pressing a key, allyour hard disk files can be destroyed. DOS 3.0 and lateradd a warning message, but an unwary user or a maliciousintruder can still easily format any hard disk.

You can protect yourself against this disaster with thefollowing batch file. It's called FORMAT.BAT. Since PC/MS-DOS will execute a .COM file before a .BAT file, you need torename the DOS formatting utility.

Change to your DOS directory, and give the followingcommand:

REN FORMAT.COM FRMT.COM

This is the first step in your protection scheme. Renamingthe FORMAT.COM allows your FORMAT.BAT file to take over whenthe command, FORMAT, is given.

Page 28

Now, create the following batch file, storing it in adirectory on your hard disk which is included in your pathstatement. Do not include the REM statement explaining howto enter the Ctrl+G command. Name the file FORMAT.BAT.

ECHO OFFCLSIF %1. == . GOTO NOPARMIF %1 == A: GOTO CORRECTIF %1 == a: GOTO CORRECTIF %1 == B: GOTO CORRECTIF %1 == b: GOTO CORRECTIF %1 == C: GOTO ABORTIF %1 == c: GOTO ABORTIF %1 == D: GOTO ABORTIF %1 == d: GOTO ABORTGOTO WRONG:NOPARMECHO ^G REM ***Hold down Ctrl and press the G key***ECHO You must enter a drive designator to format adisk.ECHO Enter the command this way...FORMAT A:... usingtheECHO drive designator for the correct drive.PAUSEGOTO END

25

Page 26: Batch.files.explained

batch_files_explained.txt 26/02/2002

:CORRECTECHO Preparing to format a floppy disk.PAUSEFRMT %1GOTO END:ABORTECHO ^GECHO ^GECHO You have specified a hard disk for formatting!ECHO You cannot format your hard disk from this batchfile!ECHO Use an alternate method!PAUSEGOTO END:WRONGECHO ^GECHO You have entered an invalid drive designator...ECHO Try again. Don't forget the colon. (:)GOTO END:ENDCLS

Let's take a look at the IF statements in this file. First,using the technique discussed earlier, the file checks tosee if a parameter has been included in the command line.If not, it branches to a subroutine called :NOPARM, whichtells the user to include a drive designator.

Page 29

Next, the batch file checks to see if the parameter enteredon the command line is a floppy drive. It tests for upperand lower case entries for drives A: and B:. If any floppydisk drive designator is given, the file branches to the:CORRECT subroutine. There, the FRMT command is given,executing the renamed formatting utility. The originalcommand line parameter %1 passes to the FRMT.COM program.

The next four lines check to see if the user entered thename of a hard disk, either drive C: or drive D:. Again,both upper and lower case are tested. If these drives areon the command line, the batch file branches to the :ABORTsubroutine. That routine sounds an alarm and refuses toformat the hard disk.

Finally, if the user has specified an invalid drive, or leftoff the colon (:) following the drive letter, the GOTO WRONGline sends the program to another routine, which explainsthe error.

Notice that each routine ends with a GOTO END line. This isvery important, and keeps the batch file from accidentallydrifting into another routine.

You can customize this hard disk protection system to fityour particular configuration. Just alter it to reflect thedrives on your own PC.

You should be able to think of a number of other ways to usethis feature of the IF command. Branching is an excellentway to add power to your batch files.

26

Page 27: Batch.files.explained

batch_files_explained.txt 26/02/2002

TESTING FOR THE EXISTENCE OF A FILE

The IF command can also check whether or not a particularfile exists. This can be very useful. For example, if youwanted to copy files from a floppy disk onto your hard disk,but only if that file already exists on the hard disk, thisuse of the IF command can save you time. You might do thisto update files on the hard disk.

Here is a batch file which does just that. Call itCOPYIF.BAT.

ECHO OFFCLSIF EXIST C:\%1\%2 GOTO EXECUTEGOTO WRONG:EXECUTEECHO Copying A:%2 to C:\%1 directory...COPY A:%2 C:\%1PAUSEGOTO END

Page 30

:WRONGECHO That file does not exist in the C:\%1 directory.PAUSEGOTO END:ENDCLS

After creating COPYIF.BAT, try it out. Put a floppy disk indrive A: which contains files which are also in a directoryon your hard disk.

Use the DIR command to get a list of files. Now type thefollowing command:

COPYIF [DIRECTORY NAME] [FILENAME]

Substitute appropriate information in the command to fityour particular directory and files. When the batch fileruns, it will check the directory (%1) for the file (%2),then copy the file from drive A: if it finds the file alsoin the directory on drive C:

Try this again, but name a directory which doesn't containthe file you name on the command line. You can see how theIF command works here.

This is a useful batch file, but it might even be moreuseful if it only copied the file from drive A: into thedirectory if that file did NOT already exist in thedirectory you name.

DOS can do this as well. To change COPYIF.BAT to performthis function, just change the third line to read:

IF NOT EXIST C:\%1\%2 GOTO EXECUTE

Make this change in your COPYIF.BAT file, and save it withthe new name COPYNOT.BAT. Try this new batch file the sameway you did before. Now it only copies the file from drive

27

Page 28: Batch.files.explained

batch_files_explained.txt 26/02/2002

A: if it doesn't exist on drive C: in the specifieddirectory. A batch file like COPYNOT.BAT is one way toprevent overwriting an existing file.

BATCH FILE LOOPS WITH FOR...IN...DO

No programming language is complete without a way ofcreating loops. A loop is a way of repeating a routine aslong as a certain condition exists. DOS allows a limiteduse of loops in batch files, using the FOR...IN...DO commandseries.

These loops are limited to dealing with filenames as thelimiting structures. Here is the syntax:

Page 31

FOR %%variable IN (set) DO command

That's slightly confusing. The %%variable is a dummyvariable, composed of a single character. An example is%%A. All this really does is give DOS a handle to workwith.

The (set) described in the syntax is a list of files. Mostoften, this set uses DOS wildcards (? & *) to representgroups of files. For example, typical sets might include(*.*), (C:\*.*) or (C:\WP\DOC\*.BAK). You can includemultiple entries inside the parentheses. To act on all.DOC,.BAK, and .TXT files, the set would be(*.DOC,*.BAK,*.TXT). You can use either commas or spaces toseparate the individual files or wildcard entries. Justremember that the set you specify is the group of files youwant to act upon.

Finally, the command part of this structure can be any DOScommand. To make this complex command series clearer, let'screate a sample batch file. What this file will do isdelete all the files with the extension .BAK in the \WP\DOCsubdirectory on drive C: This is something most users dofrom time to time. Naturally, you can substitute any otherdirectory when you create the file. Call the fileKILLBAK.BAT.

ECHO OFFCLSECHO This file will delete all .BAK files fromC:\WP\DOC.ECHO If you do not want to do this, press[Ctrl]+[Break].PAUSEFOR %%A IN (C:\WP\DOC\*.BAK) DO DEL %%AECHO All files with the extension .BAK have beendeleted.PAUSECLS

You can use any DOS command in place of DEL. If, forexample, you wanted to copy all files with the extension.COM from drive A: to drive B:, the command would look like

28

Page 29: Batch.files.explained

batch_files_explained.txt 26/02/2002

this:

FOR %%A IN (*.COM) DO COPY A:%%A B:

Similarly, to print out all your .BAT files in the \BATCHdirectory on your hard disk, the command would look likethis:

FOR %%A IN (*.BAT) DO COPY C:\BATCH\%%A PRN

Page 32

It's easy to see how useful this looping command structurecan be in your batch files. You can repeatedly perform aDOS command, controlling the files it operates on bychanging the variables in the FOR...IN...DO commandstructure. Experiment with these commands in your batchfiles.

CONTROLLING YOUR PRINTER WITH BATCH FILES

In the last part of this series of articles, I promised thatI would include a method of controlling your printer usingbatch files. While the current crop of dot-matrix printershave some wonderful capabilities, making use of them can bea chore.

You can either write a short program in BASIC to sendcommands to the printer, or use a special printer utilityprogram. Both of these systems work, but take time youcould spend more productively.

The problem lies in DOS. In its wisdom, Microsoft wrotePC/MS-DOS in a way that prevents you from sending the Escapecharacter (ASCII 27) to your printer. You can send almostany other character to the printer in a batch file with theECHO command and the redirection character (>). Any othercharacter, that is, except the Escape character.

Most printer commands are preceded with the Escapecharacter, so it's normally impossible to control yourprinter from the system prompt.

For this printer control system to work, then, you need aprogram which can do what DOS can't do. Fortunately for allof us, Calvin R. Shields has placed such a program in thepublic domain. A short program, written in assemblylanguage, it also illustrates another use of batch files.

Create the following batch file, using your favorite method.Be very careful to type the program exactly as it appearshere, including the blank lines. Call it MAKE-ESC.BAT.

GOTO STARTA 100XOR DX,DXMOV AX,001BINT 17MOV BX,0080MOV CL,[BX]XOR CH,CHJCXZ 011F

29

Page 30: Batch.files.explained

batch_files_explained.txt 26/02/2002

INC BXDEC CXJCXZ 011F

Page 33

INC BXMOV AL,[BX]XOR DX,DXXOR AH,AHINT 17LOOP 0114INT 20

R CX21n esc.comwq

:STARTDEBUG < MAKE-ESC.BAT

Notice the first line of the file, which sends the programto the :START subroutine. There, this batch file calls theDOS DEBUG program, using the redirection character to makeDEBUG assemble the program, ESC.COM, from the assemblylanguage routines included in the batch file. This is avery creative use of batch files.

Before running this batch file, make sure that DEBUG.COM orDEBUG.EXE (depending on your version of DOS) is in yourcurrent path. If you are using floppy disks, copy the DEBUGprogram onto the disk containing MAKE-ESC.BAT.

Run the batch file. You will see a brief error message,caused when DEBUG finds the first line of the program.Ignore this message. Once the file runs, you will have a33-byte program called ESC.COM on your disk. This programdoes what DOS can't do: it sends the Escape character toyour printer, which must be connected to the parallel port,LPT1:.

To make ESC.COM work, all you have to do is give thecommand, ESC, followed by a space and the command you wantto send to the printer. For example, the command whichresets an Epson-compatible printer looks like this:

ESC @ <Enter>

The simplicity of these commands makes controlling yourprinter easy. But who can remember all the commands?That's where batch files come into the picture.

To create a system for setting your printer'scharacteristics, all you have to do is write a short batchfile which gives the commands needed to set the printer.Name each batch file with an easy-to-remember name.

30

Page 31: Batch.files.explained

batch_files_explained.txt 26/02/2002

Page 34

The batch files which follow will work with any Epson orEpson-compatible printer. If you use another type ofprinter, substitute the command for your printer in thebatch file.

Let's start with the reset command, which will put theprinter in the start-up mode. Call this file RESET.BAT.

ECHO OFFCLSESC @

Here's another file. This one sets the printer to its NearLetter Quality mode. Call it NLQ.BAT.

ECHO OFFCLSESC X1

I've included the ECHO OFF and CLS lines to keep your screenclear when you issue the commands.

Here's another sample. Call this one BOLD.BAT.

ECHO OFFCLSESC E

By consulting your printer's manual, you can find all thecommands which make your printer jump through its hoops.Write a separate batch file for each command, and you willsoon have a printer control system which can handle everyfunction. You can also combine functions by entering thecommands, one-at-a-time.

If your printer is an Epson compatible, the batch files inLISTING 1 will handle almost every possible function.Again, if you use another kind of printer, consult yourmanual for the appropriate commands.

Place the batch files and the ESC.COM program in a directorywhich is in your current path. Then, whenever you need tosend a command to your printer, just give the name of theappropriate batch file as a DOS command.

The next part of this series will show you how to make batchfiles even more flexible, using additional commands andexternal programs. There are a number of commercial, publicdomain, and shareware programs which can add power to yourbatch programming.

##End main copy##

31

Page 32: Batch.files.explained

batch_files_explained.txt 26/02/2002

Page 35

LISTING 1

These batch files are designed to be used with the ESC.COMprogram in the main article. If your printer is Epson-compatible, the system will work as written. If you haveanother brand of printer, substitute the appropriatecommands. Create these files using the COPY CON command oruse your favorite text editor in its ASCII Mode.

RESET.BAT -- Sets the printer to its default mode.

ECHO OFFCLSESC @

PICA.BAT -- Sets pica (10 characters/in.)

ECHO OFFCLSESC P

ELITE.BAT -- Sets elite (12 characters/in.)

ECHO OFFCLSESC M

CONDENSE.BAT -- Sets condensed type.

ECHO OFFCLSESC ^O REM **<CTRL>+<O>**

TINY.BAT -- Sets microtype (20+ characters/in.)

ECHO OFFCLSESC MESC ^O REM **<CTRL>+<O>**ESC S1ESC 1

ITALIC.BAT -- Sets italic mode

ECHO OFFCLS

Page 36

ESC 4

32

Page 33: Batch.files.explained

batch_files_explained.txt 26/02/2002

UNITALIC.BAT -- Cancels italic mode

ECHO OFFCLSESC 5

WIDE.BAT -- Sets double-width type

ECHO OFFCLSESC W1

UNWIDE.BAT -- Cancels double-width

ECHO OFFCLSESC W0

NLQ.BAT -- Sets Near Letter Quality mode.

ECHO OFFCLSESC x1

UNLQ.BAT -- Cancels Near Letter Quality

ECHO OFFCLSESC x0

6LPI.BAT -- Sets 6 line/in. spacing.

ECHO OFFCLSESC 2

8LPI.BAT -- Sets 8 line/in. spacing.

ECHO OFFCLSESC 0

10LPI.BAT -- Sets 10 line/in. spacing.

Page 37

ECHO OFFCLSESC 1

BOLD.BAT -- Sets Boldface.

ECHO OFF

33

Page 34: Batch.files.explained

batch_files_explained.txt 26/02/2002

CLSESC E

NOBOLD.BAT -- Cancels Boldface.

ECHO OFFCLSESC F

UNDRLINE.BAT -- Underlines all text.

ECHO OFFCLSESC -1

NO-UNDER.BAT -- Cancels underlining.

ECHO OFFCLSESC -0

2STRIKE.BAT -- Starts double-strike mode.

ECHO OFFCLSESC G

1STRIKE.BAT -- Starts single-strike mode.

ECHO OFFCLSESC H

##End Listing 1##

Campbell -- Batch Power Page 38

The Power of PC\MS-DOS Batch Files

byGeorge Campbell

Part 4: Adding More Power

In the first three parts of this series on batch files, you

34

Page 35: Batch.files.explained

batch_files_explained.txt 26/02/2002

learned many of the techniques possible with PC/MSDOS batchprocessing. By now, you're probably using batch files toperform many functions you used to do, one command at atime, from the system prompt.

In this article, which will be the last part of this series,you'll learn ways you can expand your batch processing evenfurther. Although PC/MSDOS batch files have the power tomake your PC do things you didn't expect, there arelimitations to batch operations. Here are some ways to getaround those limitations:

GETTING KEYSTROKES FROM EXTERNAL FILES

One of the major limitations of a PC/MSDOS batch file is theinability to insert keystrokes into the batch file from thekeyboard. You can't stop a batch file, ask for user input,then continue with the execution of the batch file. Thereare many times when you might want to do just that.

PC/MSDOS has several commands which insist on user input.FORMAT, DISKCOPY, and DEL *.* are three of those commands.If your goal is complete automation of a command with batchfiles, these three operations will stall your batch fileuntil you type a letter.

Fortunately, there's a way to bypass this limitation. Allyou need to do is create an external ASCII file whichcontains the keystroke. Here's a good example:

In my own work, I often place files in a directory on myhard disk, called C:\TEMP. Once I'm finished working withthose files, I want to delete them from the disk. To dothis means using the DEL *.* command. PC/MSDOS, however,insists that I confirm the command by typing a Y. If I givethe command from a batch file, I still have to type theletter.

Campbell -- Batch Power Page 39

To get around this problem, you can create a file whichcontains just the letter, Y and a carriage return. I callthe file YES.ASC. Create this file by entering thekeystrokes shown below:

COPY CON YES.ASCY <Enter>F6 <Enter>

With that file stored on the disk, you can tell a batch fileto take its input from the file and send it to any programcalled by the batch file. Using the example above, here's abatch file, named KILLTEMP.BAT, which deletes all files fromthe directory C:\TEMP:

ECHO OFFCLSDEL C:\TEMP\*.* <YES.ASC

Create this file, using either the COPY CON command, or yourtext editor. Substitute a directory name which applies to

35

Page 36: Batch.files.explained

batch_files_explained.txt 26/02/2002

your computer for the one shown here.

This batch file works by using redirection. The "less than"symbol (<) tells PC/MSDOS to take directions from the file,YES.ASC rather than from the keyboard. When the command DEL*.* gives the message "Are you sure (Y/N)," it sees thecharacter "Y" included in the YES.ASC file, and thinksyou've typed the letter on the keyboard.

You can use this technique with any DOS command which asksfor a confirmation from the user. Be very careful, however,not to use the method if there is any danger of deletingimportant files.

External text files can be used to create all sorts ofuseful DOS utilities. Take the FORMAT command, for example.This program in DOS requires user keystrokes which slow downthe process of formatting new floppy disks.

If you hate the job of formatting a pile of floppies, youcan create a disk formatting utility which will formatfloppy disks continuously, prompting you to insert a newfloppy disk and press a key.

To make this batch file work, you need to create a veryshort text file which contains the keystrokes needed for thePC-MSDOS FORMAT.COM program. Call this file RESPONSE.ASC,and create it with the following commands:

COPY CON RESPONSE.ASC <Enter><Enter>N <Enter>F6 <Enter>

Campbell -- Batch Power Page 40

Once you've created that file, you can set up a .BAT file toformat diskettes continuously. Since this file is ratherlong and complex, I suggest using your text editor or wordprocessor to create the file. Remember to save the file asa pure ASCII file. Call this file CFORMAT.BAT.

ECHO OFFIF .%1 ==. GOTO NOPARMIF %1 == c: GOTO NOHARDIF %1 == C: GOTO NOHARDCLSGOTO START:STARTECHO Alt+255*ECHO COMPUTER SHOPPER'S CONTINUOUS FORMAT UTILITYECHO Alt+255*ECHO Alt+255*ECHO Alt+7*Echo Insert a new disk in drive %1 or press Ctrl+BreakPAUSECLSECHO Alt+255*ECHO Alt+255*ECHO Alt+255*ECHO Now formatting....do not disturb disk in drive %1!FORMAT <RESPONSE.ASC %1 >NUL

36

Page 37: Batch.files.explained

batch_files_explained.txt 26/02/2002

GOTO RETURN:NOPARMECHO Alt+255*ECHO Alt+255*ECHO YOU MUST ENTER A DRIVE NAME. EXAMPLE:(CFORMAT A:)PAUSEGOTO QUIT:HARDECHO Alt+255*ECHO Alt+255*ECHO YOU CANNOT FORMAT A HARD DISK WITH THIS UTILITY.ECHO NOW RETURNING TO DOS....PAUSEGOTO QUIT:RETURNGOTO START:QUITCLS

* Hold down the <Alt> key while you type the number on thenumeric keypad.

This batch file uses many of the techniques presented inearlier parts of this series, including replaceableparameters, subroutines, and conditional branching. It alsouses the RESPONSE.ASC file to feed responses to the

Campbell -- Batch Power Page 41

FORMAT.COM program. The line which reads, FORMAT<RESPONSE.ASC %1 >NUL, is the key to this utility. It callsthe DOS FORMAT routine, then directs the program to take itsresponses from the text file you created. Finally, the >NULat the end of the line keeps the normal screen messages fromFORMAT.COM off the screen.

To use this program, copy CFORMAT.BAT and RESPONSE.ASC tothe disk or directory which contains FORMAT.COM. When yougive the command, CFORMAT, add the drive name for yourfloppy disks. If you don't include a drive name in yourcommand, the program will abort and remind you. If youspecify drive C:, the batch file branches to the :NOHARDsubroutine and aborts with a warning.

The utility formats the disk, then returns to the beginning,beeps to remind you to change disks, and formats the nextdisk when you press a key.

If you have a hard disk drive and two floppy drives, anotherversion of this file can format disks in both drives,speeding up the process even further. Create this file inthe same way, but name it CFORMAT2.BAT.

ECHO OFFCLSgoto START:STARTCLSECHO Alt+255*ECHO Alt+255*ECHO COMPUTER SHOPPER'S CONTINUOUS FORMAT UTILITYECHO Alt+255*

37

Page 38: Batch.files.explained

batch_files_explained.txt 26/02/2002

ECHO Alt+7*ECHO Be sure to turn your TURBO mode off.ECHO Alt+255*ECHO ECHO Insert new disks in drives A: and B:ECHO Alt+255*ECHO To exit, press Ctrl+Break.PAUSECLSECHO Alt+255*ECHO Alt+255*ECHO Alt+255*ECHO Now formatting....do not disturb disk in drive A:FORMAT <RESPONSE.ASC A: >NULECHO Now formatting....do not disturb disk in drive B:FORMAT <RESPONSE.ASC B: >NULGOTO RETURN:RETURNGOTO START:QUITCLS

Campbell -- Batch Power Page 42

* Hold down the <Alt> key while you type the number on thenumeric keypad.

This file works in the same way, but automatically formatsblank disks in both drive A: and drive B:. Each time theroutine runs, it beeps to remind you to change disks. Itimed this routine, and it saves about 30% of the normaldisk formatting time.

You can use the same redirection technique to automate otherutility programs which require keyboard input. Try writingyour own batch file to make the DISKCOPY command runcontinuously. You'll need to write a text file, containingthe keystrokes needed for that command, plus a batch filesimilar to the ones used for the FORMAT command.

CREATING BATCH FILE PRESENTATIONS AND DEMOS

Since batch files can automate many functions on your PC,creating demos and presentations is a natural use for thesePC-MSDOS programs.

A presentation or demo is typically a series of screens,displayed in order. Using batch files to make the processautomatic can let you concentrate on your presentation, andnot on operating the PC.

The first step in creating a demo is to create the screensyou want to display. Use your word processor or text editorto create as many screens as you like. If you use WordPerfect or another program which can do line drawing andboxes, you can enhance these screens. Many word processorscan also use the <ALT>+numeric keypad technique to displayextended ASCII characters, adding even more visualpossibilities.

Keep each screen down to 24 lines of text or less, so thewhole screen can be displayed without scrolling. Save yourscreens in ASCII format, naming them SCREEN1.TXT,

38

Page 39: Batch.files.explained

batch_files_explained.txt 26/02/2002

SCREEN2.TXT, etc. Number the files in the order you want tofollow with your demo or presentation.

Now, create the batch file you'll use to display yourscreens. Call it DEMO.BAT, or any other name you like.Again, use your text editor or word processor to create thefile. Leave out the REM commands and messages when youcreate the file.

ECHO OFFCLSPROMPT Alt+255 REM Eliminates the DOS prompt.TYPE SCREEN1.TXTPAUSE>NUL REM Shuts off the "Press a key" message.CLS

Campbell -- Batch Power Page 43

TYPE SCREEN2.TXTPAUSE>NULCLSTYPE SCREEN3.TXT....TYPE SCREEN(n)CLSPROMPT REM Restores the dos prompt.

Expand this batch file to include all of your presentationscreens. When you run DEMO.BAT, it will clear the screen,turn off the DOS prompt and load the first screen. Tochange screens, just press any key on the keyboard. Thescreen will clear and the next screen will appear.

You can use the same program to create presentations forother users, as well. Just leave the >NUL off the PAUSElines in the batch file. Now you can mail a disk containingyour demo to another user. When that user types thecommand, DEMO, your screens will display, with the line,"Strike a key when ready," at the bottom of each screen toprompt the user for a keystroke. Even unskilled PC userswon't have any trouble displaying your demo with thissystem.

You'll find other uses for this presentation system. I useit for displaying the documentation for shareware programs,and for sending letters and other documents to PC users.

BATCH FILE EXTENSION SOFTWARE

There are a number of commercial, public domain, andshareware programs designed to enhance your use of batchprogramming. Using these external programs, you can addeven more power to your batch files. You may already haveone or more such programs in your software library. Here'sa brief rundown on some of the best:

THE NORTON UTILITIES

This powerful collection of utilities contains several

39

Page 40: Batch.files.explained

batch_files_explained.txt 26/02/2002

programs design to enhance your batch operations. If youhave this software, try out the following programs from thecollection:

ASK: This program does what DOS can't do, acceptingkeyboard input from users during the execution of a batchfile. Especially useful in batch file menus, like the onesdescribed in the first part of this series, ASK allows you

Campbell -- Batch Power Page 44

to get a keystroke, then branch accordingly. This eliminatesthe need for additional batch files to call programs.

BEEP: While you can cause your PC to beep in batch using theECHO Ctrl-G command, Norton's BEEP command allows you tospecify what kind of tone you get. You can even createfiles to play simple tunes using this command.

SA: Short for Screen Attributes, this program allows you toalter your computer's screen characteristics. You can setup screen colors and other attributes by including thiscommand, plus parameters in your batch files. This one isespecially useful for the presentation system discussedabove.

For more information on THE NORTON UTILITIES, contact PeterNorton Computing, Inc., 2210 Wilshire Blvd., #186, SantaMonica, CA 90403. Phone: (800) 451-0303, Ext. 40.

EXTENDED BATCH LANGUAGE

This is a shareware program, designed specifically toincrease the power of your batch files. Using it, you canaccept user input, perform arithmetic functions, search forfiles, and control the appearance of your computer's screen,or use many more of the program's functions. This program isa complete programming language in itself.

If you're serious about batch programming, this program is amust for your library. Like all shareware, you're free totry it out without charge. The author requests aregistration fee of $49 if you continue to use the program.That fee brings you additional functions and a completemanual.

EXTENDED BATCH LANGUAGE is available for downloading onGEnie and Compuserve, and can be found in the catalogs ofmost shareware distributors. It's also available directlyfrom Seaware Corp., P.O. Box 1656, Delray Beach, FL 33444,Phone: (305) 392-2046.

FSTSCRN2

This public domain program performs a very useful function.It converts an ASCII file, no more than 24 lines long, intoa .COM file. By giving the name of the file as a command,you cause it to display on your monitor.

What makes this program exciting is the way these converted

40

Page 41: Batch.files.explained

batch_files_explained.txt 26/02/2002

ASCII screens pop onto the monitor almost instantly. Usethis program for menu screens, help screens, and screensused in the presentation system described above.

Campbell -- Batch Power Page 45

Rather than displaying the screen with the TYPE command,just give the screen's filename as a command and you haveinstant response. FSTSCRN2 can add a professional look toyour batch files.

Download the program from CompuServe or GEnie. It's alsoavailable on many local BBS systems.

THEDRAW

Designing attractive screens can be a problem. Using a wordprocessor, especially when you want to include extendedASCII characters for simple graphics, can be a complicatedprocess.

THEDRAW is designed to solve just that problem. Written byCalifornia programmer, Ian Davis, it is a complete screendesign utility. Using this program, you can create complexand attractive screens for menus, presentations, or demos --and you can do it quickly.

The program even allows you to add color changes within yourscreen and, using ANSI.SYS in your CONFIG.SYS file, you caneven create animated screens. THEDRAW screens are displayedwith the TYPE command.

Available on CompuServe, GEnie, and from most sharewaredistributors, the program is shareware, with a registrationfee of $10. Contact the author directly at TheSoftProgramming Services, 1929 Whitecliff Court, Walnut Creek,CA 94596.

BOOTS

This is a collection of three public domain utilities, whichyou can use in batch files to control booting your PC.WARMBOOT.COM simulates the <Ctrl>+<Alt>+<Del> keystrokecombination and causes a warm boot of your PC.

COLDBOOT.COM, the second program, simulates a cold boot.Instead of hitting the reset or power switch, you can rebootby giving the command, COLDBOOT.

BOOTNOT.COM prevents a user from rebooting with the<Ctrl>+<Alt>+<Del> key combination. This is very useful,especially if inexperienced users might destroy data on yourPC by accident.

The other two programs can be included in batch fileswhenever you need to reboot your system. One possible usewould be to remove memory-resident programs. I use it this

41

Page 42: Batch.files.explained

batch_files_explained.txt 26/02/2002

Campbell -- Batch Power Page 46

way to remove a memory-resident program or a RAM disk whichmight interfere with another program.

BOOTS is available on GEnie and CompuServe for downloading.

FIXBEEP

Most users are quickly annoyed with the monotonous beepproduced by their computers. If you've ever dreamed aboutreplacing that beep with another sound, FIXBEEP is theanswer.

Written by Mike Blaszczak, FIXBEEP, allows you to changethat sound to anything you want. The program is shareware,but the registration fee is only $5.

Use fixbeep in your batch files to change the beep tone.You can alter the tone to signal different operations inyour file, signalling the user to take action. For example,to change the normal beep to a short, high-pitched sound,include the following command in any batch file.

FIXBEEP /F3000 /D50

This command would produce a tone with a pitch of 3000hertz, lasting for half a second.

FIXBEEP is available on The Source, CompuServe, and GEnie,as well as from the author. Contact Mike "Nifty James"Blaszczak, 112 Verlinden Drive, Monroeville, PA 15146.

TOGGLE

There are many occasions when you might want to turn theCapsLock or NumLock function on or off from a batch file.The two programs in TOGGLE, CAPLOCK.COM and NUMLOCK.COM,allow you to do just that.

I use NUMLOCK.COM in the batch files which call myspreadsheet and accounting programs. It saves me from themistakes I usually make by forgetting to press the NumLockkey.

TOGGLE is in the public domain, and is available fordownloading on GEnie and Compuserve.

E88

If your word processor can't save files in ASCII format, orif you would just like to have a simple, fast text editor

42

Page 43: Batch.files.explained

batch_files_explained.txt 26/02/2002

Campbell -- Batch Power Page 47

for creating and altering batch files, E88 may be just theeditor you need.

It produces pure ASCII files, and has a text searchfunction, along with block moves and other editing functionsyou'll find useful for batch programming.

E88 is easy to learn, fast, and, for programming purposes,is often better than a full-fledged word processor. Theprogram is shareware, but the author asks only $10 as aregistration fee.

E88 is available for downloading from GEnie and CompuServe,or you can contact the author at M.R.E. Software, 150 JonesSt., West Point, MS 39773

SPECIAL OFFER

As a service to the readers of this series on batch files,I'll be happy to send readers a disk containing all thepublic domain and shareware programs mentioned above. Tocover the costs of copying and mailing, send $7.50 for a5.25" floppy disk or $10 for a 3.5" disk to:

George Campbell1472 Sixth St.Los Osos, CA 93402

Be sure to mention the batch file articles, and specify yourdisk size. All of these programs contain their owndocumentation in an ASCII file which you can copy to yourprinter. If you use these programs regularly, please honorthe shareware concept by sending the registration fee to theauthors who request it.

TIPS FOR EFFECTIVE BATCH PROGRAMMING

1. Plan your batch files before you begin to write them.Make a list of the functions you want to perform, then begincreating the file. Always give batch files easy-to-rememberfilenames to avoid errors.

2. Include lines which use the ECHO command to print screenmessages. Users, yourself included, will benefit fromscreen messages which explain what's going on during batchfile execution.

3. In any batch file which uses replaceable parameters,include an IF line to check whether or not a parameter wasgiven with the command. If not, GOTO a subroutine whichexplains the correct syntax for the batch file. TheCFORMAT.BAT in this article is a good example.

Campbell -- Batch Power Page 48

4. If you have a hard disk, create a directory calledC:\BATCH, and store all your batch files in that directory.

43

Page 44: Batch.files.explained

batch_files_explained.txt 26/02/2002

If you include the directory in your PATH command, you'll beable to access your batch files while you're in anydirectory on your hard disk. Here's a sample PATH command:

PATH = C:\;C:\DOS;C:\BATCH

Thanks to reader Roger Paulson for reminding me of thisimportant tip.

5. You can give the command to execute another batch file inany batch file. To return to the original batch file, justgive its filename as the last line of your second file. Youcan't call the current batch file, however, from within thatfile.

6. Use the <ALT>+255 technique to create blank lines withthe ECHO command, and to eliminate the DOS prompt with thePROMPT command. This works with all versions of DOS, from2.0 on. Be sure to leave a space between the command andthe key combination, and always use the number pad to enterthe numbers.

Note: You can also insert any extended ASCII character,such as the ASCII graphics characters, using the sametechnique. Just substitute the correct ASCII code in placeof the 255 code for a blank character. You'll find a chartshowing these codes in your DOS manual.

7. Don't use the DOS redirection characters (< and >) inECHO, PROMPT, or PAUSE lines in your batch files. DOS seesthem as part of a command and will respond with the "Badcommand or filename" error message. Substitute brackets([]) or curly brackets ({}) instead.

8. When testing new batch files, you'll often encountererror messages. These usually mean you've misspelled acommand or left out a space after ECHO, PROMPT, or PAUSEcommands. Check for these errors first.

9. Memory-resident programs sometimes conflict with eachother. If you encounter unusual problems after adding amemory-resident program's command to an AUTOEXEC.BAT file,try changing the order of the programs. You may have to tryseveral orders to make your memory-resident programscooperate.

10. Finally, experiment with batch files. Anytime you findyourself typing the same series of DOS commands, considercreating a batch file to automate your computing.

44