Now that you've taken the time to
review the Batch File Basics,
here are almost forty tips to help you when composing and running
your batch files. As you get experienced at writing them, you will
find referring here will be less necessary because you will be able
to keep much of what you are doing straight in your head.
However, if you write batch files
infrequently, or you haven't done one in a while, the tips presented
below will be of assistance.
Realise that not everything suggested below may
work for your manufacturer or version of DOS. Refer
to the appropriate documentation so you may adapt
your system to work with what what is presented here.
INFORMATION BELOW MAY NOT BE REPRODUCED
WITHOUT PERMISSION FROM THE AUTHOR ©
- Outline a Prospective File.
Before firing up your text editor, outline on scrap paper what the
batch file is for and what each step should do. Be sure to include what
the file is not supposed to do, as well. Then compose the file
with the commands necessary to achieve that end.
- Write Batch Files in ASCII (Plain)
DOS requires ASCII text in order to understand a batch file and
execute it. If you've used a word processor and failed to save the file
in plain text, it will not execute properly, if at all, and you'll receive
an error message.
- Use a Title and Comments.
Displaying a title and using comments within a batch file will help
you and others to know what a file, or part of a file, does. This is helpful
when viewing or editing a file at a later date when you've forgotten what
it does and/or how it does it.
- For Complicated Batch Files,
Write One Section at a Time.
Trying to think out and then code a complicated series of
instructions is difficult, even for experienced batch file authors. Start
with a basic file and build upon that.
So for an operation such as one that identifies certain files, then
moves some, deletes others, and finally backs up the result, start with
the basic identifications and have the results echoed to the screen. Try
this batch file segment under differing conditions and when the correct
files are consistently being shown it means the identifications are likely
Now code the MOVE and DEL operations and test. When these are correct,
write the BACKUP section. Finally, combine each segment into a cohesive
batch file and add any interlinking coding that is required for the segments
to work together. This "buildup" method makes for easier debugging and keeps
you focused on one task at a time.
Another advantage of writing and understanding individual segments means
that they can be incorporated into future batch files in a "mixed &
matched" style. This is similar to how an interior decorator might use
parts of certain looks from past undertakings to build his or her vision of
an entirely new project. Essentially, these segments become part of your
- Use a Template.
Most batch files will start with a commented area containing the
file's name, a short description, and perhaps a syntax example. Then there
will usually be an "@Echo Off" command. The last line might contain the
word "END" or perhaps a DIR listing. If enough files you compose contain
these elements, make up a template with them in the file. Save it as
"Template.txt" and place it in your BATCH directory. Set its attribute to
read-only.(*) Then write a batch file to call this file into your favourite
editor where you may then insert the appropriate commands for the new batch
file you are about to make. When finished, save it under the name of your
new batch file.
(*) Since the template file has a read-only attribute, it cannot be
accidentally overwritten if you forget to rename it when saving the new
batch file. For more on this technique, see
- Use Double Colons for Comments.
To prevent comments from resulting in error messages, use a double
colon ( :: ) before each line containing any remarks. The "REM" command
may be used instead, but DOS will read the entire line and actually perform
some things such as redirection and piping. That could cause problems under
certain circumstances, so employing the double colon is a better method.
When DOS comes across a double colon, it ignores everything from the
second colon onward because this second colon is an illegal label
character. (The single colon is used as a label precursor in batch files.)
DOS immediately skips to the next line after reading a double colon. I also
place a space after the double colon. This gives an extra degree of
readability when perusing a lengthy batch file.
(See Batch Basics for how this method
is used. You may also be interested in the lesson on
An alternative to the above is to use GOTO statements. This makes for a
cleaner batch file, but does cause DOS to have to re-read the file to look
for the label being referenced. Despite the re-read, this technique could
be used for long comment segments.
:: Batch File Name
(Place syntax, notes, or other instructions here so that
you may in the future discern what the file does and how
it does it.)
(Batch File Continues)
DOS will skip that text section because it is told to go to the "START"
label. As such, no error messages will ever be produced because DOS never
executes those lines. However, it will read them, so be aware that excessive
comments could introduce a noticeable delay on slower systems.
- Incorporate Blank Lines and Indenting.
This separates each part of a file and aids in readability. Indenting
is useful for sub-routine sections, although some programmers indent all
lines between labels. Neither blank lines nor indents affect the running of
the file because after an "Echo Off" command, DOS ignores any it encounters.
- Be Consistent with Text.
Use the same style for all composing. This could be upper, lower, or
mixed case and the use of blank lines and Indenting for certain purposes.
Keep labels consistent from file to file, as well. This allows one to fall
into a pattern that will aid in deciphering a file at a later date.
It's also handy should you decide to slightly alter a batch file for
another, but similar purpose, while keeping the original. These similar
batch files will have exactly the same layout. This is good for later
deciphering, and for consistency among types used for a similar purpose.
- Anything Permissable at the Command Line
may be Used in a Batch File.
Whatever steps you type at the command line to execute a task may
be included when composing batch files. In fact, the simplest, basic batch
files are made up of such lines. Now some things such as percent signs and
quotation marks must be doubled in some cases, but legitimate commands can
always be included.
Of course, batch files can include more complicated operations that go
beyond most command lines in most versions of DOS, but don't forego the
basic DOS command issuing methods when composing your batch files.
- Learn to Use Switches and Exit Codes.
The usage of a command's switches allows one to tailor it to run in
varying ways apart from its basic operation. Couple this with making use of
that command's exit codes and one may write very powerful batch files that
function on their own. Without any further input, such batch files can make
decisions based on your pre-selected criteria. You may apply the same idea
to utilities and even major applications in order to tailor their usage to
your criteria. (See the DOS Switches and
Exit Codes discussions elsewhere at this
- Separate Switches from their
Commands and Parameters.
As at the command line, I suggest that spaces be placed between any
commands and their switches, and must be placed between parameters such as
replaceable characters or file names. Think of each as a word in a sentence.
With no spaces, DOS may assume anything lumped together to be a single
parameter, not the separate ones you intend.
Although DOS can often execute a command and its switches with no
spaces, not using them could cause problems depending on the way your DOS
version interprets what is a parameter and what is not. To eliminate any
ambiguities, always space commands and switches. That way, there is no
question as to what is a separate parameter and what is not.
Some switches may be able to be grouped as opposed to using a separate
slash for each. I prefer to use separate slashes, again for faster
readability, but also because it is easier to interpret spaced, single
letters compared to a group of crowded letters. This is especially so when
taking into account all switches for all programs. Some use words, others
use single letters, and some use both. Single letter switches stand out more
from word switches when the former are not grouped.
- Arrange Switches in Alphabetical Order.
As an additional aid to reading a batch file, arrange switches in
alphabetical order. This not only makes for that easier read, but for a
command directive incorporating many switches, it's easier to locate the one
wanted (or see if it's even included at all) when one can look in a specific
alphabetical spot for it.
Be aware that there are times with both DOS and DOS software when
switches must be placed in a certain order. Learn those times and obey the
required order. The times will be few, though, so don't obsess over this
issue. (For an example, see "Debug Your Files", farther on.)
- Keep Labels to a Minimum.
When most DOS versions read a batch file, they read one line,
execute it, and then read the batch file from the start to locate the
next line. If there are excessive labels, it will take DOS slightly longer
to execute the file because once "GOTO (label name)" is encountered, DOS
must first locate that particular label and then run the succeeding line.
So whenever you can write a batch file that executes in sequence, choose
it over one that does much jumping around. This won't matter with fast
processors and/or short batch files, but complicated ones may execute
noticeably slower. As such, it is best to be in the habit of writing
sequential operations whenever possible.
Note that newer versions of DOS don't read and re-read a batch file. In
particular, with 4DOS' .btm batch files, the entire file is read into memory
and then is executed a line at a time with no re-reads unless a GOTO is
encountered. Even then, the re-reads are not done from disc, but from
- Use Labels to Identify Sections.
Whenever you make subsections in batch files, be sure to label the
start of each section -- even if the label will never be referenced with a
"GOTO" statement. This makes for an easier read and easier debugging at a
later time. It also helps when trying to understand the flow of a batch
Now you're thinking: "Doesn't this contradict the last tip?" No, it
doesn't. Since the labels are never referenced by GOTO statements, DOS
never has to look for them. It simply reads past them as it does in the
ordinary execution of a batch file.
You could also use the double colon (::) for this purpose. However, I
prefer to reserve that for comments and use labels for each section of code
in batch files. Yes, I know it's only the difference of one colon, but I am
picky! (-: Humour aside, even though it's only one colon, it allows me to
quickly identify a label compared to a comment when doing a fast scan of a
batch file's code. Also, I can input `::' for a text editor search and find
comments quickly while skipping all labels, which employ only one colon.
- Use the `@' Character to Prevent a Line from
being Echoed to the Screen.
The `@' (asperand or at) sign may be used at the beginning of any
line in order to suppress that line from being seen on screen. This is
useful at the start of a batch file to prevent "ECHO OFF" from showing
up, but may be used any time ECHO is set to `On' in order to prevent a
given line from appearing on the screen. (Again, you may wish to review
- Use ECHO to Place Screen
Having DOS notify you as to what a batch file is doing is handy.
This is especially important when an operation is expected to take some
time. It might even appear to the user that the computer has locked up if
nothing appears on the screen to alert that user. A message could say
something such as Update Operation In Progress -- Please Stand By...
to calm an infrequent user of that batch file. Use tabs to place messages
away from the left margin to make them easier to spot on a crowded screen.
Keep those on-screen prompts and messages short. Long messages tend to
be glanced over, meaning a user might miss something important. As well,
long messages may wrap at awkward points especially if the batch file is
run in a window or on a hand-held device with less than an 80-column
- Use ECHO. to Create Blank Lines
" ECHO. " (Echo Dot) will place a blank line on the screen in most
DOS versions. Doing this before & after a message separates it from
preceding and succeeding text or the DOS prompt. (Note that there is to be
no space between the "ECHO" command and the dot.)
If this does not display a blank line with your DOS version, try placing
a colon ( : ) or an ASCII space after the "ECHO" command. You may make such
a space by pressing & holding the "ALT" key and then typing "255" on the
keyboard's number pad. Upon releasing the "ALT" key, an ASCII space will be
produced. (Note that some text editors may use a different method for
producing this character -- consult your manual.)
- Use the PAUSE Command to Halt a Batch
After this command, DOS places a message on screen asking if the user
wants to terminate the batch file. Then it waits for user input. Pressing a
key will resume the batch file operations. ("Control-C" will terminate
operations. See farther on.)
- Use the SHIFT Command when more than
Nine Parameters are Required.
SHIFT moves all parameters down by a factor of `1' each time it
is executed. This way, a tenth parameter becomes #9 and may be accessed
by referring to it as `%9'. Issuing SHIFT again makes %9 equal to what
had originally been the eleventh parameter, and so on. (Note that some
DOS versions allow designations of parameters higher than `%9', as does
4DOS, and in a related manner so do DOSKEY and Toddy.)
- Allow Your Batch Files to Wait a Bit by
CHOICE has an option to wait `n' seconds and then execute one of
the choices as pre-selected by the batch file author. The limit is only
99 seconds, but may be useful if a short delay will suffice. The syntax
would be something such as:
CHOICE /C:d /N /Td,60
The `/C' switch shows the available choices. (In this case it's only `d'.)
`/N' tells CHOICE not to display the choice to the user, while `/Td,60'
tells CHOICE to employ a delay of 60 seconds and then to execute Choice
`D'. See the `/T' switch option of CHOICE in your DOS documentation.
To obtain longer delays, run CHOICE through a "FOR-IN-DO" (FOR) loop
FOR %%D IN (60 120) DO CHOICE /C:d /N /Td,60
This delays for 120 seconds.
- Use ANSI.sys to Add Colour and Form to
Dress up your batch files by using ANSI.sys to add colour to your
messages. You may also wish to reserve certain colours for specific
purposes. A warning message might be in red; a cautionary message in
yellow, with green perhaps being reserved for those prompting the user to
follow a specific action. Colour is ideal if there are multiple messages
to be placed one after another. It more easily allows the viewer to
discern them as individual messages.
You cay also place messages anywhere on the screen using ANSI.sys'
cursor positioning capability. Lines and boxes may even be drawn to
underline or surround your on-screen text.
- Give Full Path names for all
This allows DOS to go immediately to the directory required, thus
saving a path search. So, as an example, if the MOVE command is to be used,
issue it as "C:\DOS\MOVE..." rather than just "MOVE..." .
This method can also be extended to issuing full paths for the files on
which actions are to take place. This means that a command will act upon
only files on the stated drive and in the stated directory. This is good
because if the batch file were to inadvertently be run in a wrong
directory, unexpected things might happen. Unintended files might even be
deleted or modified. Directing DOS to the place where you want actions to
occur, even if it is still within the current directory, is a wise and
- Place Often-Used Operations in Their Own Batch
If many batch files run, say, a directory listing at the end, or
display the same closing screen, don't add these lines to the end of every
file. Instead, place them in their own batch file and refer to it at the
end of each file. This saves a lot of typing. Plus, should you change this
closing screen, directory display, or whatever, only one file needs to be
changed instead of every instance in every file.
This same tip applies to complicated on-screen messages. If it's to be
used often, place it in its own .txt file and have the affected batch files
tell DOS to display it as necessary. Again, if a change is required, it will
only ever be needed to be done once for the file that holds that message,
not in every batch file that uses it. This is most handy for menus that
contain a long list of text selections and many ANSI colour and/or position
- Leave Clean-Up Until the End.
If ending a batch file requires resetting parameters, deleting
temporary files and/or directories, and/or resetting or removing environment
variables, do that at the very end of the batch file unless required
beforehand. This is especially important if a final display will appear. It
will be on the screen sooner if the command to do so is issued before those
commands that will do the clean-up. Then while you are viewing the display,
clean-up will be happening in the background. This will make your batch
files seem to run faster.
This method can also be used within a batch file any time a display
command is issued for which the user will be reading for a bit. This
is, of course, if the deletions and resettings can be made part way
through the running of the batch file without affecting the running
of the rest of that file, or without having to be reissued. Reissuing
could mean extra, unnecessary work for the batch file, possibly slowing
its execution. Being able to do clean-up during a batch file while the
screen is being read by the user means less to do at the end and thus, a
slight speed advantage as perceived by that user.
- Incorporate Utilities to Extend a
Batch File's Capabilities.
There are zillions of DOS utilities available that can do one
or a few operations very well. Use them to increase the usefulness of
your batch files, or to save having to code those operations yourself. As
examples, I often use XSET and XXCOPY to perform tasks that would take
many lines of code, and consequently much of my time to write. Without
them, long work-arounds might be required to coax DOS to do things for
which it was never programmed or for which it has no built-in commands.
In addition, I find PC Tools and Norton Utilities to be helpful. Each
one in the package is a separate executable and can be run independently
of its parent shell program. Thus, they can be easily used by batch files
to perform tasks.
- Do Not Use the Name of Another File as a
Batch File Name.
This may cause user confusion, and under certain circumstances one
file may conflict with the other, producing unexpected results. This is
especially a problem if the batch file has the same name as a 4DOS alias,
a DOSKEY or Toddy Macro, or an internal DOS command. The batch file won't
execute because these DOS commands take precedence. Similarly, if one tries
to run a batch file from a directory that contains a .bat file having the
same name as a .com or .exe in that same directory, the intended batch file
will not run. This is because DOS gives precedence to .com and .exe files
over .bat files when they have the same name.
Another conflict could arise with directories that come before BATCH in
the PATH statement. If the batch file name is the same as a program or
another batch file that happens to be located in a PATH statement directory
that comes before BATCH, it will be executed instead of your batch file
because DOS will find it first.
Experienced users can ignore this tip if they know their systems well,
and in addition have limited their PATH to essentially just the BATCH and
DOS directories, or made them the first two directories in the Path. Thus,
one may have a WP.bat if the WordPerfect directory is after the BATCH one,
or not included in the PATH statement at all. (See Remove Programs from
the Path, farther on.) However, if one was to issue "WP" while in the
WordPerfect directory, the program would run and not the batch file, so
none of the extra commands in that batch file would ever happen.
- Rehearse Your Batch Files in a "TEST"
Make a test directory with a couple of sub & sub-sub directories.
In it. Place new batch files, along with various small files copied from
other directories. (The usage of small files is so that your tests will
run faster.) Then run the batch file to be sure it does what you want, and
more importantly, see that it doesn't do want you don't want.
If anything bad happens, it will likely only affect the test directories and
their files. If you can't see what is wrong with a non-functioning batch
file, debug it as described in the next tip. Once you are confident of the
file, it may then be placed into the regular BATCH directory.
As your batch file experience grows, you will need the TEST directory
less because you will most often write batch files that work pretty much
correctly on the first try. Still, for complicated files, a test directory
is a must, even for experienced batch-file writers.
- Do Not Code In Message Suppression
The tendency for experienced batch-file writers is to suppress
messages for smoother operation purposes. However, do not suppress them
until the bugs have been worked out. On-screen messages will give you a
better idea as to what is going on. When all is well, feel free to insert
code to eliminate messages and other prompts as desired.
- Debug Your Files.
In keeping with the above two tips, run the batch file to see what
it does or doesn't do that was not intended. If a problem arises and you
cannot see what is the cause, use:
COMMAND /Y /C (batch file name) (parameters/switches)
...to step through each line of the file. When a line executes in a way
unintended, you've located the problem. See STEP.bat in
Batch File Examples for a detailed example.)
Note that the sawitches must be on the order shown and that not all DOS
versions are capable of this. 4DOS users may do it by issuing
SETDOS /Y1 ^ (batch file name).
Those using earlier DOS versions, may remove or "REM" (Remark) out the
"Echo Off" command to see each step as DOS executes it. If it is still
undetermined which line might be the problem, place a PAUSE command before
a line suspected of causing an error and run the file. If all is well,
move the PAUSE to before the next line. Continue to do this. It will
allow the file to run until an error is encountered. Error messages or
errant operation will be viewed at the point of error, and the file
will pause its execution.
Note regarding REM: A better method is to use a double colon and a space
in place of "REM". See farther back in this article and also
Batch Basics for more on this.)
- When Debugging a Batch File, Make One
Change at a Time.
When you discover an error in a batch file while testing it, or
if you decide to rewrite a section, make only one change at a time. Making
multiple changes may result in multiple problems. Alter only one line change,
test the file. This will allow you to see what that particular change did.
Using this method makes for much easier error correction and teaches you how
batch files "think".
- Increase the DOS Environment Space.
Making good usage of the environment makes one a DOS power user. As
this usage grows, you may see Out of Environment Space messages. To
increase its size, modify the "SHELL" directive in your CONFIG.sys, or
use an "Environment" statement in the DOS.ini (initialisation) file, if your
version uses one. Typical syntaxes are:
SHELL=C:\DOS\COMMAND.COM C:\ /e:1024 /P
1024 bytes should be enough for most purposes unless your batch files
incorporate a lot of "SET" statements or you use very long names and/or
- To Stop a Batch File, Use "Control-C".
If something is not happening as you expect and the file continues to
run or has locked up, press ^C (or ^Break) to stop it immediately. Answer
`Y' to the prompt, `N' if you wish it to continue.
Note, that to assure this works, set "Break" to "On". I have the
"Break=On" command as part of my AUTOEXEC.bat so I know it's on all the
time. Be aware too, that some programs turn off "Break" when loading. To see
if this is the case, at the command line, issue the "Break" command with no
parameter. It should be "On". If it's not, add "Break=On" as the last
line in your AUTOEXEC.bat. If some programs do not act as desired when
issuing a ^C, you will have to add "Break=Off" to the beginning of the batch
file that starts the program and "Break=On" to the end of the file. Most
programs like this will turn it off automatically, so you'll only need the
closing "Break=On" line.
- Remove Programs from the Path.
Once you use a batch file to start a program, take its path and name
out of your PATH statement. Since the batch file will start the program from
any where in DOS, it need not be able to be located by DOS in order to start
because the batch file directs DOS as to exactly where it is. A shorter path
makes less search work for DOS, thus speeding up path and directory exploring
Note however, that some programs require PATH statement inclusion if
they sometimes operate outside their own directories. After removing the
program from your path, if it does not function properly, see if in the
program's setup you can specify the program's path and file locations. If
so, modify that parameter. If not, place code to temporarily include the
program in the path before it is run, and then more code to remove it
Some programs also allow an environmental statement that tells the
program where to find its files. This is accomplished through the "SET"
command. In your batch file, place such a statement on the line immediately
preceding that which starts the given program. Place another "SET" command
on the line immediately after the program-starting one to restore the values.
This last step is important because these environment statements take up
memory and could cause troubles if other programs use an environmental
variable with the same name but containing a different value.
Another method is to use APPEND statements in the batch file. If a
program fails to function properly after trying each of these, you may have
to restore it to the path. (Be aware that I have never had to do this and I
have myriads of programs on several partitioned drives spread over three
computers.) See your DOS and/or program manuals for more on the "SET" and
"APPEND" commands. Also, see this website's
DOS Tips section.
- Use a Disc Cache.
Most DOS versions read a batch file a line at a time, starting from
the top of the file for each line being executed. So after Line `1' is read
and executed, DOS re-starts at the top, sees line `1', then looks at Line
`2' and executes it. It then reads from the top looking for Line `3', and
so on. If the file must be read from the hard drive for each line, this
takes time. It would be better if the file could be read into memory once
and then DOS could look through memory rather than reading from the hard
drive. 4DOS and other new DOS versions do this, but older DOS versions use
the method described above.
One way to get older DOS versions to read the file from memory is
accomplished by using a disc cache. The file is read into the cache and
DOS will look there before trying to read from the hard drive. This is much
faster. Another method to speed execution is to place all batch files on to
a RAM drive. (See the next tip.)
- Load Batch Files on to a RAM Drive.
Use a small-size RAM drive with small cluster sizes to preserve
memory. Then place the RAM Drive batch directory at or near the start of
your path statement. Your batch files will run much faster because they are
always in memory. Automate the process by placing statements in your
AUTOEXEC.bat to create a RAM drive and then a BATCH directory on that RAM
Drive. Next have it copy the batch files to it.
- Assign Your Most-Used Batch Files to
Function or other Keys.
Then you are only a keystroke away from your most common work. I use
my DOWNLOAD, UPLOAD, and TEMP directories continually throughout the day, so
I make them immediately available via "Alt-D", "Alt-U", and "Alt-T". Hitting
any of those key combinations, runs the batch file for me and takes me to
the chosen directory. It then displays that directory in wide format,
alphabetical order, and with each file type in a different colour.
- Buy DOS Books.
DOS has been around long enough that many publications are easily
available in used books stores at excellent prices. You don't necessarily
need one geared to your DOS version; just look for a good chapter or section
on Batch Files. Of course, additional information presented on DOS doesn't
hurt either. A good library of books is a must if you are thinking of
becoming a power user, or just wish to improve your DOS operating system
knowledge. See this website's DOS Publications
section to get started.
Once you are familiar with that information, modern facts on batch files
may be had from your on-screen "Help" files or from numerous websites. See
the Batch File Tips, Tutorials, and Utilities section of
DOS Websites elsewhere at this website.
Be sure to locate books with included discs. Many will have very
useful utilities -- even for today. Remember, DOS has remained true to
itself; old DOS programs will run on new versions and new software will
run on old DOS versions, with few exceptions.