|
Doctor DOS Betamax's |
DOS
|
|||||||||||||||
|
|
||||||||||||||||
|
Batch files make one a power user; becoming |
|||||
|
Go Directly to the Tutorial
A Simple Menu System
This is an elementary introduction to writing DOS batch files. Simple code will be shown to ease the novice into this aspect of automating computer procedures. After the tutorial will be links to example files which may be copied or downloaded for your own usage. Each example will be explained as to what it accomplishes and what individual lines do towards that end. An additional section of almost forty batch tips will aid you when composing your own files, and finally you may obtain 500+ batch files that I employ for my own everyday computing purposes.
This tutorial will assume that you are running DOS exclusively, although Linux, Macintosh, OS/2, Unix and Windows users may also make some, if not complete, usage of DOS batch files. However, users of those systems will likely need to modify the examples in order for them to comply with other systems, or a DOS emulator will be required. Be aware though, that these emulators are not 100% compatible with real DOS.
It is assumed you know the basics of DOS command issuing, its file & directory structures and its conventions, plus have some understanding of paths and the path statement.
Realise that Doctor DOS will not be responsible for problems
encountered through the use or mis-use of anything presented here.
"What is a batch file and why might I need one?"
A batch file is a plain text file containing a series of commands that
you might ordinarily issue at the system prompt in order to perform a
computer operation. The most common uses are to start programs and to run
utilities. Batch files do that with one command instead of the multiple
commands usually required. They can be likened to shortcut icons as seen
in point & click operating systems, but batch files are much more
powerful.
Using a batch file to start a program often means that your path statement may be made shorter. This results in having fewer directories through which DOS must search during its operations. Having a shorter path will also leave room for other programs that may require path inclusion in order to function properly.
Further, sophisticated batch files can improve upon program starting by loading all or part of the program into upper or expanded/extended memory, thus freeing up more lower (conventional) memory. Allowing lots of lower memory means your programs have breathing room and there will be space for utilities to run. This same capability may be had at the command line, but the commands will likely be intricate and difficult to remember. Why not let a batch file do the work for you?
With one command, a batch file can start the program in the desired configuration and furthermore, can request an associated file such as a word processor document or spreadsheet be loaded once the main program is running. This saves the user a search for that document and the issuing of the commands necessary to load it. One simple command of the user's naming does it all.
This is similar to Window's "File Association" feature, but with more advantages because a number of batch files could be written to load the same file, each with its own, but different, attributes or start-up options. In fact, one could even have the same file loaded into different programs, each time with specific, yet different, options. The user never has to change these configurations manually.
To re-enforce: Once set up, batch files can automatically load
any program (with or without documents) in the user's chosen
configuration and with the user's selection of options. At
the user's whim, the documents, configuration, and
options can be made different each time -- all
controlled directly from the command line,
and from anywhere within DOS.
Using a batch file to run a utility means being able to have direct access to it at the command line and from any place. This can already be achieved by including the directory containing the utility's executable in the path. However, if there are any often-used specific options, these can be placed into a batch file, and thus save you from having to type them each time you use that utility. Even better: Using a batch file means no possibility of forgetting or mis-typing these parameters.
Batch files can also be trained to make decisions that perform operations only if certain conditions exist or don't exist. The most sophisticated ones can even emulate commands not normally included with the DOS operating system.
WHAT YOU'LL BE DOING:
The first section, below, will help you to understand and then write
a basic batch file. For those who are afraid of programming, this article
will show you how simple it really is. DOS batch files are a good place to
start learning programming because they use plain-English commands for the
most part. Thus, they are easier to comprehend, even for those of you whose
first language is not English. Batch files also teach logical flow and error
correction -- all things used in more sophisticated programming, should you
move on to such endeavours.
You may then go to other sections which will show you to how improve the batch file, how to make it present attractive screen messages, and how to make the batch-file code be easily deciphered when looking back at it from some future point. You'll also see how to combine small batch files to do sequences of operations.
On the Advanced Batch Files page, you'll be shown examples of more complicated batch files which use command-line parameters. These allow the file to function in different ways depending on the circumstances and the desired outcome. On the other advanced pages, there are batch files given that prompt a user for input. These permit operations based on choices made by the user once the file is running.
You may wish to rename the example files and perhaps use a different path structure. Go ahead -- this tutorial is just for basic learning purposes. You may also see another use for a batch file if it had some modifications. Be creative and try the changes; a reminder though: Be aware that no responsibility will be taken by Doctor DOS for any problems encountered when using (or mis-using) anything presented at this website.
I suggest that you always try out any batch file in a TEST directory. Copy some files there to try out the batch. If it works as you intend, and more important, if it does not work as you do not intend, then transfer it to your regular working batch directory. If anything did go wrong in the TEST directory, it would only affect copies of files and not corrupt or destroy the originals.
The first item above means to issue some initial instructions that prepare the main program or utility to run, or to prepare it to start a task. These might be to go to a specific directory, create or change an environment parameter, place a message onto the screen, or anything else needed for a program/utility to run as you or it requires, as dictated by the task to be done.
This preparation stage might also include instructions for saving the current environment and directory. This is so that when the batch file ends, one is returned to the exact place and working environment as before the batch file was run.
The next point in the list runs the program or utility as directed by you, or in some cases, by the batch file itself under the guidance of some pre-selected criteria.
Finally, the last point means to display closing messages or a directory listing as confirmation of a utility operation. It might delete temporary files made by the batch file, or it might restore the program or DOS to its default settings, or to the ones saved in the first step. The latter might be to deposit the user in some specific directory after the program or utility has finished, or as mentioned, to return to where one was before running the batch file.
"What do I do first?"
To begin, create a directory called "C:\BATCH" where you will place your
new batch files. Some people use "C:\BAT", but that bothers me because there
would then be a directory with the same name as the batch file extensions,
which must use ".bat". For housekeeping and organisational purposes, I try
to not use names more than once -- especially where conflicts might arise or
confusion might be generated.
Next, modify your path statement as found in your "AUTOEXEC.bat" file to include this new directory. You may use the text editor that came with DOS, or one of your choosing. I suggest placing this new directory at the start of the PATH statement so that DOS will find and execute your batch files quicker by not having to search through unnecessary directories first. I have my "Batch" directory placed first and also right before the DOS directory. So the path statement might read in part: PATH=C:\BATCH;C:\DOS; and so on. It's also important that the BATCH directory be before any program directories. This is because any program executable with the same name as the batch file will initiate first, bypassing your carefully crafted batch commands. After saving this file, type "\AUTOEXEC" (or "C:\AUTOEXEC" if you are not on the `C' drive) and press "ENTER". You may also reboot to initiate this change.
After the AUTOEXEC.bat completes, select a text editor to use in writing each line of your file. You may employ the one you used above, but there are many other text editors available that you may find are more to your liking. The only thing required is that it be able to save these files in plain DOS (ASCII) text. This can be done by all text editors such as DOS' Edlin and Edit, Windows Note/Wordpad, and a host of independent editors. Word processors such as Wordstar, WordPerfect, MS Word and Writer also have the capability as long as you be sure to save the document in ASCII (plain text) format.
Type the example files into your text editor as you see them here. DOS is not case sensitive except in certain instances. These will be noted if necessary. Otherwise, one may type all upper, all lower, or some combination. I prefer to use all-caps for this purpose, except for certain instances, or when case sensitivity is an issue. Alternatively, you may screen capture or download this page and edit everything out but the batch file(s) you wish to use, or copy & paste just the batch text into a blank file.
When finished, name the file as seen here, or use some other name that you'll remember and be able to associate with the batch file and what it does. I suggest that you stick to original DOS file-naming conventions of up to eight characters before the dot and using a `.bat' extension so that DOS will know it's a batch file and run it as such. Newer DOS versions allow longer file names but I don't recommend their use. Besides causing extra typing in order to run the file, if you decide to use it yourself on an older system, or pass it on to someone using an older DOS version, a long file name is likely to cause problems.
Recalling the file-name conflicts I touched upon farther back, you should not name your batch file the same as any other file which is on your computer, if possible. Otherwise, whichever comes first during a DOS path statement search, will execute. This is unless one is in the directory in which the given file resides. In that case, the current directory's file takes precedence. There may be some cases where one wishes to use a batch file with the same name as another file, but to eliminate unexpected results, it's generally best to not use files with the same names. For programs, however, I do tend to use the same name as the given program's executable unless it is a long name. This is not generally a problem because I have no program directories in my path, and I almost never manually start programs from their own directories, unless I am testing something related to that program. In addition, for clarity's sake during this tutorial, I will use `WP' as the name of the batch file so that you will easily associate it with WordPerfect.
Finally, remember to place your new file into your "C:\BATCH" directory.
Once you understand the basics, we'll discuss some
improvements to make the file do more things with
the same simple keyboard command. This technique
will be followed throughout these lessons.
YOUR FIRST BATCH FILE:
Let's select a task that involves only a few steps. I often use
WordPerfect, so we'll do that one first. Ordinarily, without a batch
file or without WordPerfect's executable in the Path, one would log on
to the appropriate drive, change to the WordPerfect directory, and then
issue the command to start WordPerfect. A batch file will do this for you
automatically. As you will see, each main line in this example batch file
emulates what one would ordinarily type when at the command line.
I'll first show you the complete batch file and then explain what each line does. The following assumes that you are using WordPerfect 6.0 and that it resides in a WP60 directory on the `C' Drive. Change these parameters if they differ from your word processor and directory.
Note that the indentations shown for each example are to make them stand out in your browser. You don't need to indent the lines in the batch file itself unless you want to have them as part of your batch file layout look. Indentations made by tabs or spaces after "ECHO OFF" are ignored by DOS during batch file execution.
:: WP.bat :: Runs WordPerfect 6.0 :: @ECHO OFF C: CD\WP60 WP.exe
The first line is the batch file name. This is useful to remind anyone looking at the file as to which one it is. The second line is a title remark that identifies what the file does.
Note the use of twin colons. DOS will not execute any batch file line with twin colons in front of it, nor display it on the monitor screen. After seeing the second colon, DOS ignores it and anything following, then goes to the next line. That is because the colon is an illegal label character. With regards to batch files, a DOS "label" is a word or a series of numbers/characters used to identify a part of a batch file. Some people use a single colon to place remarks in a batch file, but since DOS uses this to identify its labels and those lines will be read, I suggest the single colon not be used, except of course, as a label precursor. (You'll read more on labels in the tutorial's examples.)
Alternatively, others will use "REM" which is short for "Remark". DOS does not execute these lines either, but it does read them, slowing things down. This is not a problem with today's fast processors and hard drives, but can make a difference on slower computers when the batch file is long and contains a lot of remarks. Regardless, my philosophy is that anything which speeds operations should be used.
I must mention there is also a problem with "REM" lines which contain redirectors and piping, which I won't get into here because it is beyond the scope of this tutorial. I simply recommend the double colon as the best symbol for placing remarks/comments into a batch file.
Getting back to the example batch file: For the third line I employ the double colons with the remainder of the line blank. It is used as a separator between the title and the file itself. Although they do not affect the running, or contribute to the mis-running of the batch file, they should be used here because DOS will display an unnecessary prompt on the screen for any blank line before an "ECHO OFF" command.
The fourth line is required to tell DOS to not display the succeeding lines on the monitor screen, and the "@" symbol tells DOS to not show the line itself. The first command in typical batch files usually is "ECHO OFF". "Echo" means that the keys struck on the keyboard are "echoed" (displayed) on the screen. Since a batch file is just a series of commands, what is typed in the file would be echoed on the screen as DOS executes each of those lines, just as though you were typing each instruction at the command prompt. However, in most cases, the user is only interested in the end result and does not need to see everything that DOS is doing. Using the "Echo Off" command means each command issued by the file as it works toward completing the requested task will not be echoed to (appear on) the screen. Again, if you wish even that line to be hidden, add the `at' symbol ( @ ) before it, as in the example above.
Next is a blank line. DOS ignores blank lines (if they occur beyond an "Echo Off" command), and executes the following line immediately. I insert such lines to separate the various steps the file does to complete its assigned task. It makes no difference to the running of the file but does give each part its own space, making for better readability. This is important for lengthy, complicated files, especially if you go back into them a long time after they were written.
The succeeding line tells DOS to go to the `C' drive. This is important if you are logged onto a floppy, CD-ROM, RAM, or flash drive, or onto another hard drive, yet wish to start word processing immediately. The next line changes to the WP60 directory and the final line tells WordPerfect to start.
Note that I used the full executable name (WP.exe). I always do this as a precaution against companion viruses. I won't get into a long explanation here but a companion virus substitutes its own executable for common program-starting commands. In this case, it might substitute WP.com for WP.exe. Whenever you ran WordPerfect as `WP' (not the batch file), the virus would run first and spread itself throughout your system.
Be aware that some programs use their own batch files to start themselves.
When writing batch files to start those programs you must refer your batch
file to that batch file. This should take the form of: |
There you have it. Save that as "WP.bat" in your BATCH directory. Now to start the program from the DOS prompt, type "WP" from any drive or directory, (except the WP60 directory). If it works, you may now remove "C:\WP60;" from your path statement, making for a more efficient running of DOS. Since the batch file changes to the correct directory for WordPerfect, DOS does not have to search the path to locate the WP executable file. Since it no longer has to search, having WordPerfect in the path statement is unnecessary. The fewer directories through which DOS must search, the faster it locates what it wants, resulting in a more efficient, and thus faster, operation of your computer.
Be sure to tell WordPerfect where its files are via the program's set-up section. If this is not been done, removing its directory from the path may result in some error messages while running WordPerfect. Typically, pressing Shift-F1 will display the set-up screen when in WordPerfect. |
IMPROVEMENTS:
"Can this file do more work for me?"
I have a screen that is my opening one after boot-up and it's the one to
which I always return after exiting any program, save for a few. It's my
desktop, which for me, is the `C' drive root directory with a specific
custom prompt and a directory listing using an after-market program called
Color Directory by Loren Blaney. It gives a wide-format display of
the contents of the directory with sub-directories and file types in
different colours. You could display the directory contents by incorporating
DOS's "DIR" command, if you wish, but Color Directory dresses up the
screen and makes it easier to discern file types.
To return to my example desktop after exiting Wordperfect, the screen must be cleared, the `C' Drive root directory must be returned to, and the Color Directory listing displayed. Now, we could add these commands to the end of the above batch files, but since I want to this to happen after running most batch files I write, it's a better idea to have this be its own batch file, and then have other batch files refer to this new one as part of its list of commands. It will save typing those commands into every batch file, but more important is that should you decide to change your desktop, only this one specific file needs to be altered, because all others will refer to this one.
:: CLR.bat :: Clears Screen and Returns to the DeskTop :: @ECHO OFF C: CD\ CLS C:\BATCH\DR.BAT
We have already discussed the opening information lines, the "@ECHO OFF" command, the double colons and blank lines, so I will skip them here and for all future discussions. Lines 6 & 7 return one to the `C' Drive's root directory. Line 8 is the DOS "Clear Screen" command. It erases everything on the screen except for the prompt and any special screen settings contained within, such as certain coloured text & backgrounds, among other options.
The final command is for the Color Directory. It's also a batch file (called "DR.bat") with one line (after "@ECHO OFF") that directs DOS to the directory containing the Color Directory program's executable file. The full path is given so that DOS will not have to search any directories for the "DR" batch file. I have named this batch file "CLR.bat", which stands for "Clear Screen, Return to Desktop".
I can now add this "CLR" command to the end of any batch file to clear
the screen and return me to my desktop automatically after completing any
task. The reason this works is that after a DOS batch file hands control
over to a program, when the program finishes, it returns the reins to DOS
which remembers that there is another line in the batch file to run. It
therefore runs the "CLR" batch file upon exiting a given program, which
then returns me to my desktop.
:: WP.bat :: Runs WordPerfect and Returns to the Desktop :: @ECHO OFF C: CD\WP60 WP.exe C:\BATCH\CLR.bat
FURTHER ENHANCEMENTS:
"Could this file do yet more work?"
The preceding improves the original "WP.bat", but we can enhance it
further through WordPerfect's built-in command-line options. I won't get
into an explanation of its options here because that would be outside the
subject of this article. You'll need to consult the WP manual to learn
more; however I'll give you an example of some.
I like to have WordPerfect use expanded memory (/r), and have it place and read its overflow, buffer, and temporary files on to my RAM (F) Drive (/d-) for faster operation and the freeing of lower memory. With these options, the batch file now becomes:
:: WP.bat :: Runs WordPerfect and Returns to the Desktop :: @ECHO OFF C: CD\WP60 WP.exe /r /d-F:\TEMP C:\BATCH\CLR
Note to use this, you will have to create a TEMP directory on your RAM drive upon each bootup. Add such a line to your AUTOEXEC.bat. If you don't make use of a RAM drive (you should!), create the TEMP directory on your C drive and point WordPerfect there. It won't be as fast, but there will be fewer files for WordPerfect to look through when it doesn't place its temporary files into its own, already crowded directory.
WordPerfect, as do many DOS programs, can also load a document upon startup. You might like to use a letter form (which is called a "template" in the word processing world) for most letters you type. Its name might be "LETTER.FRM" and it would likely include your name & address as a header, along with various options you like to use. (Never use the extension "TMP" for a "template" file as that may be used by DOS and its programs to designate a temporary file). If your letter form is sitting in a subdirectory of WordPerfect's called "Template", the third-last line of the batch file becomes:
WP.exe /r /d-F:\TEMP C:\WP60\TEMPLATE\LETTER.FRMThis batch file version might be called "WPLET.bat".
Now that you have this basic batch file, a large stable of batch files could be written to run WordPerfect and load any number of different documents. In addition, you may also have your batch file start a WordPerfect macro using WP's `/m-' switch. A macro is a type of batch file used by many programs. You write it much as you would these DOS batch files except a ".wpm" extension is used in WordPerfect. (See your word processor's manual for details regarding macro writing.)
To run a WordPerfect macro from your DOS batch file, enter the macro option after any other options for WordPerfect. Now, with one simple command, you can start the program from anywhere within DOS, load a letter template, and then have the WP macro load the current project on which you are working into that template. The line might then look like:
WP.exe /r /d-F:\TEMP C:\WP60\DOCUMENTS\LETTER.FRM /m-PROJECT.WPM
All this is from one simple batch file that might be named "WPCP.bat" for "WordPerfect, Current Project". What a huge amount of typing saved! Can you imagine pointing & clicking through all that, or typing all those lines every time you wanted to work on that particular project? Of course, one could have a desktop icon for it, but when a huge number of files with different options results in a screen full of dozens of icons, such a system bogs down. With the batch file method, you get the options you want, tailored to each type of program and document upon which you are working, without having to reconfigure a program's defaults.
Note that these command-line options are done using "slash switches", that is a slash followed by a letter or character string. For more on this aspect of DOS, see DOS Switches, elsewhere at this website. Making use of command line options (switches) is a very powerful way to run programs.
As your projects change, rewrite the WP PROJECT.wpm to reflect the latest one. Thus "WPLET.bat" will always load the latest such project without you having to remember its name. |
If you always load the current project into the same template (which would be typical), after the first time, save the WP project and template as one, under the project name. Then redo the batch file to have WordPerfect load the project file directly, rather than having it load a template and then run a macro to load the project into that template. It saves a step and gains a small speed advantage. |
In closing, a batch file may be made up
from any system prompt commands.
This allows one to funnel multiple-line
typings down to just one simple command.
I have gotten asked for simple menu system examples so that
users won't have to type in a program's name to start it.
Here is a very basic one, and an improved version afterward.
First you will create four batch files, one for each program. I will call each program by a letter to keep it simple. You would substitute the actual program's directory name and executable for each batch file. Save each batch file to C:\BATCH.
:: A.bat :: Runs The First Program :: @ECHO OFF C: CD\A A.EXE MENU.BAT ________ :: B.bat :: Runs The Second Program :: @ECHO OFF C: CD\B B.EXE MENU.BAT ________ :: C.bat :: Runs The Third Program :: @ECHO OFF C: CD\C C.EXE MENU.BAT ________ :: D.bat :: Runs The Fourth Program :: @ECHO OFF C: CD\D D.EXE MENU.BAT
Now create the menu batch file. I will call it "MENU.bat" here for clarification purposes; you may name it anything convenient.
:: MENU.bat :: Displays the Menu Choices on Screen :: @ECHO OFF CLS ECHO. ECHO. ECHO Press `A' to Start the `A' Program ECHO Press `B' to Start the `B' Program ECHO Press `C' to Start the `C' Program ECHO Press `D' to Start the `D' Program ECHO. ECHO.
This is a very simple display. One could dress it up with lines, boxes and/or colour, but that is beyond the scope of this beginner's tutorial. The batch file starts by clearing the screen and adding a couple of blank lines. Then the text of each line is echoed (shown) on the screen with two more blank lines at the bottom.
After a program runs, DOS will return to the batch file to run the "MENU" command, thus assuring that the menu will always appear. If a menu item is not wanted, one can enter any DOS command because one is at the command line anyway.
That's it! Enter "MENU" to display the menu (remembering to have C:\BATCH in the path statement.) At this point, the four lines will display on a cleared screen. Press one of the letters, and the program will start. It's that simple!
The interesting thing about this method is that one need not display the menu first. Once you know the start command for each program, press `A', `B', `C', or `D' anywhere at the command line to start one of the programs.
AN IMPROVEMENT:
Instead of having five batch files, the preceding can be done with one.
:: MENU.bat (Improved) :: Displays the Menu Choices on Screen :: and Allows Selection of One. :: @ECHO OFF :START CLS ECHO. ECHO. ECHO Press `A' to Start the `A' Program ECHO Press `B' to Start the `B' Program ECHO Press `C' to Start the `C' Program ECHO Press `D' to Start the `D' Program ECHO Press `E' to Exit to the Command Line ECHO. ECHO. C:\DOS\CHOICE /C:ABCDE /N > NUL IF ERRORLEVEL 5 GOTO END IF ERRORLEVEL 4 GOTO A IF ERRORLEVEL 3 GOTO B IF ERRORLEVEL 2 GOTO C IF ERRORLEVEL 1 GOTO D GOTO START :A C:\A\A.EXE GOTO START :B C:\B\B.EXE GOTO START :C C:\C\B.EXE GOTO START :D C:\D\D.EXE GOTO START :END CLS
This uses the DOS "CHOICE" command. A full explanation will not be given here so as to maintain simplicity. Essentially, the choices are displayed and DOS waits for the user to select a letter. Whatever letter is chosen takes the batch file to that letter and the appropriate program is run.
After the selected program finishes, DOS returns to the next line in the batch file which is to go back to the start and once again to display the menu. The exception is when the user selects `E'. This skips any further program commands and goes to the end whereupon the screen is cleared and the user is deposited back at the command line.
Note that users must have a DOS version that supports "CHOICE".
Batch files put one on the way to power-user status. As
you go through the example pages at this website, you will
often see the same batch file fragments used over and over. As
you become proficient at writing them, you will begin to build a DOS
toolbox of batch techniques that can be mixed and matched to achieve
your desired results, so you can then automate all tasks that you attempt.
|