Smart Computing ® Smart Computing ®
Top Subscribe Today | Contact Us | Register Now   
middle
Home | Tech Support | Q&A Board | Article Search | Subscribe & Shop   


Run Commands In Batches Email This
Print This
View My Personal Library

Beyond The Basics
January 2001 • Vol.12 Issue 1
Page(s) 78-81 in print issue
Add To My Personal Library

Run Commands In Batches
Batch Files Using DOS Shortcuts Simplify Many Functions
DOS is the operating system that was used by PCs before the advent of Windows. Rather than use a GUI (graphical user interface), you typed in commands with DOS. For example, you type dir to see a list of files, cd to change subdirectories, and del to delete files. Because you type the commands on a blank line, DOS is said to have a command line interface.

While DOS is no longer visible under Windows, it is not gone. If you need to perform serious hard drive maintenance, you can have Windows boot to DOS or you can select Restart The Computer In MS-DOS Mode from the Shut Down menu. (You do not have these options if you're running Windows Me.) You can also access DOS by selecting Run from the Start menu and typing command. Check the Program list off the Start menu. You may be able to open the DOS Command Prompt from there as well.

Regardless of how you reach DOS, once it is running you issue the commands. For example, you might change to the NETSCAPE CACHE subdirectory and delete all the old cache files or change to the TEMP subdirectory and erase orphaned Windows Temp files. You can collect commands that you enter in DOS into a DOS script file, called a batch file.

DOS batch files offer several advantages over issuing the commands from the command line.

It is much easier to remember the name of a batch file than the DOS commands needed to accomplish a given task.

You can collect many DOS commands in one batch file to run them together.

It is safer for inexperienced users to issue the commands using a batch file than to try and use those commands themselves.

As an additional advantage, C:\Autoexec.bat runs automatically when you start or reboot your computer. However, this too was removed in WinMe.



How Do I Create A Batch File?

Batch files need to be in your path (more on that later) in order for you to be able to easily start them from the command line. The easiest way to do that is to create a new folder just for batch files and make sure it is in your path. We recommend naming a folder BATCH on the C-drive: C:\BATCH. By using this folder only for batch files, you'll quickly and easily see what scripts you have available, and you can copy them to other computers as desired.

The batch file itself must be a plain text file, and the file must have a .BAT extension. The easiest way to create a batch file is with either Notepad or Wordpad. Notepad automatically creates text files. In Wordpad, the default file format is Word, but from the File menu, click Save As and in the Save As Type field, select Text Document MS-DOS Format and click Save.

The commands that you place inside the batch file will, for the most part, simply replace commands that would otherwise be issued from the command line. For example, in the Root.bat file you can change to the ROOT directory of the C: drive so you can see its files. Root.bat contains five lines:

Root.bat
@ECHO OFF
C:
CD\
DIR
PAUSE

@ECHO OFF. This should be the first line of every batch file. It keeps the commands from being shown on the screen (echoed) as they are executed. You still see the results, just not the commands. When a batch file is not working properly, however, you'll find it useful to remove this line so you can see the commands as they execute and get a better idea of what is causing the problem. If you type ECHO followed by a message, the message displays on the screen.

C:. This changes to the C: drive. Most of the time, you're already logged in to the C: drive so this isn't necessary, but if you're looking at the CD or diskette drive, typing this line in lets you start back in the C: drive. Planning for contingencies is one of the more difficult aspects of successful programming, including batch scripting.

CD\. This line changes to the root directory.

DIR. This shows a list of all the files.

PAUSE. This is a special batch command that causes the batch file to display a message and wait for the user to press any key before resuming. You won't need it here because the batch file does nothing after the command, but it shows you how to make the batch file to wait before continuing.

While Root.bat is informative, it does not really do anything useful. Let's look at a useful file. If Netscape Navigator is your browser and it is installed with the default settings on a PC with a single user, it stores its cache in the C:\PROGRAMFILES\NETSCAPE \USERS\DEFAULT\CACHE subdirectory. While you can empty the cache from within Navigator, it is easier to use the Cache.bat file.

(NOTE: You should only run this batch file after you've closed Navigator.)

Cache.bat
@ECHO OFF
C:
CD "\Program Files\Netscape\Users\default\Cache"
DEL *.HTM?
DEL *.JPG
DEL *.GIF
DEL FAT.DB
DIR
PAUSE

The second line, below, changes to the C: drive, and the third changes to the appropriate subdirectory. Lines 4 through 7 delete the files typically found in the cache. The next line displays a list of any remaining files so you can see if anything was missed and the final line pauses the batch file.

Before using the Cache.bat file, make sure you've specified the correct subdirectory for the cache because the batch file will try to delete these files even if the command to change to the cache subdirectory fails. We didn't include the DEL *.* command in this batch file to minimize the damage in case the cache subdirectory is improperly specified.



An Easier Way To Run Batch Files

Cache.bat thoroughly empties the Navigator cache. Clearing the cache from within Navigator does not reduce or delete the database file called Fat.db that Navigator uses to track the Web pages stored in the cache. Cache.bat can be hard to run if you must first start a DOS session and then type CACHE to run the batch file, but Windows makes it easy to run any batch file.

To install a batch file on the Desktop, right-click the desktop and select New and Shortcut. That brings up a wizard that prompts you for three pieces of information. First, it prompts for the command line. If you have saved the batch file to the BATCH subdirectory, look for C:\Batch\ followed by the name of the batch file, including the .BAT extension. Next, it prompts you to enter a name to use for the shortcut, and finally it lets you select an icon. Once installed, double-click the batch file's icon to run it. The DOS window will not close when the batch file finishes, but we'll show you how to change that momentarily. You can, of course, close it manually by clicking the Close button.

You can also add batch files to the Start menu. To do so, right-click the Start menu and select Open. Navigate to the folder you want to put the batch file in and select File, New, and Shortcut from the menu. From there, follow the instructions in the previous paragraph. The batch file will now run just like any other item on the Start menu.



From the Program tab in the Clear Letters Archive Bit Properties dialog box, you can set up a Shortcut Key to run a batch file.


Fine Tuning Its Operation

Once you've installed a batch file to run from either the Desktop or Start menu, Windows lets you customize how it runs. To do this, right-click its icon and select Properties. The resulting dialog box has six tabs, but we'll focus on the two used to customize the batch file's operations.

The first is the Program tab. Using this tab, you can control the following:

Working. This is where Windows starts the batch file. Once you've started the batch file, you can move it to any desired location by issuing the necessary commands.

Batch file. This line is misleading because it actually has nothing directly to do with this batch file. Rather, Windows has the ability to run a batch file to configure DOS before running any program. Because the batch file can configure DOS as required, there is no need to use this setting with a batch file.

Run. This controls the type of Window in which the batch file runs. A normal window is best for most batch files.

Close On Exit. Check this box and the DOS window will automatically close when the batch file is finished. Automatically closing the window works well if a batch file does something and then quits, but if you need to read any messages, you won't want the window closing before you read them.

The other tab used with batch files is the Memory tab. Batch files can store pieces of information in memory, and other batch files can read that information, which lets batch files communicate with each other. The "environment" is the area of memory used for this purpose. You'll only use the Memory tab when the batch file needs to use the environment. By default, the Initial Environment setting is Auto, but this does not allow the batch file to use the environment properly. You should change the setting to its maximum value, 4096. Most batch files do not use the environment and will not require this change.



More Uses

Let's say that you constantly take work home with you. Not only do you need to grab the correct file to take home but you also need to take the same files back to work with you in the morning in order to keep your two machines synchronized. Further, let's assume that you store all of this work in your MY DOCUMENTS folder on both your work and home computers and that both machines have a Zip drive as the D: Drive. You could try to remember to copy the files to and from the Zip drive, but you may not remember every single file you made changes to. You can automate the process with batch files so one copies the files to the Zip drive and a second file copies them from the Zip drive.

Copy.bat
@ECHO OFF
XCOPY "C:\My Documents\*.*" "D:\My Documents\*.*" /M /S

If your work files do not exceed the storage capacity of your Zip drive, you can use commands, such as those in the Copy.bat file to copy all of the files you've changed from the C: drive to the Zip drive. Windows maintains a setting called the Archive Property that flags a file that has changed since it was last backed up. The /M switch tells the Copy.bat file to copy only files that have been changed, and the /S switch includes all lower level folders in the copy. Using the /M switch resets the Archive Property so Copy.bat won't copy the file next time unless you've modified it.

Get.bat
@ECHO OFF
C:
CD "\My Documents"
XCOPY "D:\My Documents\*.*" "C:\My Documents\*.*" /S
ATTRIB *.* /S -A

Once the modified files are on the Zip drive, you'll need to copy them from the Zip drive to your computer. Get.bat lets you do just that. This batch file copies all of the files from the Zip drive to the target C: drive. The /S switch is used to include lower level folders, but you won't need the /M switch because you know you want all of the files on the Zip disk. Copying the files from the Zip disk turns on the archive switch, and the last line turns it off. That way, in the morning it doesn't look as though these files have been modified unless you had worked on them at home.

As long as you run the Get.bat batch file before any files are modified on the target computer, these two batch files will keep both computers synchronized. Once the files are copied off the Zip disk, you can use Explorer to erase the disk, or the batch file could do it for you.

In this example, we have assumed that all of the files are in the MY DOCUMENT subdirectory. The nice thing about the batch file approach is that the number of subdirectories does not matter because adding an additional subdirectory to the synchronization process simply means adding a line to Copy.bat and Get.bat. That means we can synchronize multiple subdirectories as easily as we can synchronize one.

Start-Back.bat
@ECHO OFF
C:
CD\Windows
CD "Start Menu"
XCOPY *.* "A:\Start Menu\*.*" /S

If your number of files grows too large to fit on a Zip disk uncompressed, you can swap XCOPY for the command line version of the compression program PKZIP in the two batch files. Batch files and PKZIP make a wonderful combination to selectively back up files to either a Zip disk or, in the case of smaller files, a diskette.

StartDOS.bat
@ECHO OFF
PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;C:\UTILITY;C:\BATCH
DOSKEY /bufsize:5000 /keysize:100
SET DIRCMD=/on

Start-back.bat uses a similar approach to make a backup of the subdirectories and shortcuts that make up your Start menu. It will copy the shortcuts to a diskette because they tend to be fairly small. You could use a similar approach to back up a student's files at school or a child's homework at from a home PC.

If you work in DOS, you likely start DOSKEY when you run DOS, and you may set the path. Startdos.bat sets the path, starts DOSKEY with a large buffer, and configures the display order for the DIR command. The path is a list of subdirectories you want DOS to search anytime a command is entered; you'll separate each subdirectory in the path with a semicolon. DOSKEY is a program that lets you recall prior DOS commands. By opening the Properties dialog box for the DOS session and specifying Startdos.bat as the batch file to run when it starts, your DOS sessions will always be configured to your liking.



Advanced Batch Commands

Although batch files mainly contain DOS commands, there are a few special commands you can use to add intelligence to your batch files. We will look at two of the most useful. Normally, batch files process lines sequentially. The GOTO command lets the batch file jump to a new line. The line to jump to must begin with a colon followed by a single word name with nothing else. The command GOTO NAME will then jump directly to that line. Look at the Jump.bat file to see an example. The third line of the batch file is never executed because the batch file jumps over it.

Jump.bat
@ECHO OFF
GOTO END
ECHO This Line Is Not Executed
:END

Using a batch file to jump over lines is not a terribly useful function in-and-of itself. However, when combined with the IF logic test, the batch file responds to its environment and shows some basic intelligence. Consider the Cache.bat batch file for example. It tries to delete cache files even if they don't exist. Cache2.bat combines IF with EXIST to check that the Fat.db file exists before trying to delete the cache files. Because this should only exist in the cache subdirectory, the batch file "knows" it is in the correct subdirectory if it finds this file, and it knows the files have not already been deleted.

Cache2.bat
@ECHO OFF
C:
CD "\Program Files\Netscape\Users\default\Cache"
IF NOT EXIST FAT.DB GOTO END
DEL *.HTM?
DEL *.JPG
DEL *.GIF
DEL FAT.DB
DIR
PAUSE
:END

You can check for a specific file anytime you know a certain file will always exist in the target subdirectory. It is particularly useful when the file name is fairly unique.

Batch files can receive input from the user, but you must enter it on the command line after the name of the batch file. Each word you enter on the command line is then stored in a variable. The name of the batch file is stored as %0, the first word as %1, the second as %2, and so on. The variables stop with %9, and you'll need advanced commands to access any inputs beyond %9.

Tell.bat
@ECHO OFF
ECHO %%0 is %0
ECHO %%1 is %1
ECHO %%2 is %2

These variables can be used in messages or acted on in commands. For example, Tell.bat displays the contents of the first three (%0-%2) variables. Dirmask.bat displays the files that match the wildcards entered when the batch file is started. Type DIRMASK *.BAT, for example, and you will see all the batch files in the current subdirectory.

Notice that Dirmask.bat uses a logic test IF (%1)==() to make sure the user enters a file mask. If the user does not, it displays an error message and then jumps to the end of the batch file. This is another example of a batch file adjusting to the situation.

Ncd.bat
@ECHO OFF
IF (%1)==() ECHO Must Enter Abbreviation
IF (%1)==() GOTO END

IF (%1)==(win) C:
IF (%1)==(win) CD\Windows
IF (%1)==(win) GOTO END

IF (%1)==(bat) C:
IF (%1)==(bat) CD\Batch
IF (%1)==(bat) GOTO END

IF (%1)==(doc) C:
IF (%1)==(doc) CD "\My Documents"
IF (%1)==(doc) GOTO END

:END

If you are an old-hand at DOS, you remember a Norton Utility called NCD (Norton Change Directory) that let you quickly move between various subdirectories using an abbreviation. Thus, typing the command, NCD WIN, takes you to the Windows subdirectory no matter what drive or subdirectory you are currently in. Ncd.bat recreates much of the functionality of this handy utility using a batch file.

Ncd.bat first checks to see that the user entered an abbreviation. If not, it displays an error message and jumps to the end of the batch file. After that, it checks the abbreviations one-at-a-time. When an abbreviation matches the ones built into the batch file, it changes to the correct drive, changes to the proper subdirectory, and then jumps to the end of the batch file.

DirMask.bat
@ECHO OFF
IF (%1)==() ECHO No File Mask Entered
IF (%1)==() GOTO END
DIR %1
:END

The logic tests in Ncd.bat are case sensitive so if you type Win, it won't match the check in the batch file for win, nor will it find a match for Windows. The usual approach is to write the batch file to test for each of three possible capitalizations: lowercase, uppercase, and initial capitalization. A section must be added for each of these capitalizations for each abbreviation.

Due to space limitations, this article has just scratched the surface of the batch file scripting language and the potential uses for batch files. If you find yourself working with DOS on occasion and issuing the same commands over and over or wishing you could expand the usefulness of DOS, then you owe it to yourself to explore the power of DOS batch files in more detail.

by Ronny Richardson





Want more information about a topic you found of interest while reading this article? Type a word or phrase that identifies the topic and click "Search" to find relevant articles from within our editorial database.

Enter A Subject (key words or a phrase):
ALL Words (‘digital’ AND ‘photography’)
ANY Words (‘digital’ OR ‘photography’)
Exact Match ('digital photography'- all words MUST appear together)





Home     Copyright & Legal Information     Privacy Policy     Site Map     Contact Us

Copyright © 2010 Sandhills Publishing Company U.S.A. All rights reserved.