A batch file is nothing more than a collection of DOS commands placed into an ASCII text
file. When DOS executes a
batch file, each line in the file is treated as a
DOS
command and is executed as if you had typed the command at the system prompt. Their main use is to automate DOS command
sequences you
repeat often or are hard
to remember.
Each line in the file is treated as a DOS command and is executed as if you had typed the command
at the system prompt.
In addition
to standard DOS commands, batch files also have their own
subset of commands which allow you to actually write a batch file as a small program. Branching and iteration are allowed
in these programs.
Also, batch commands may have external parameters passed to them at the time you execute
the
file.
A batch file must have the extension .BAT and you execute the commands in it like any other DOS command:
by
typing the file's root
name, without the extension,
at the system prompt. Parameters are extra pieces of information that you type after many of the DOS commands. For
example, "DIR B: /W" contains the parameters B: and /W. These modify the basic operation of the
command, but are not required
by
the command.
You pass parameters to a batch file in the same manner; by typing the information after the
batch command,
but before tapping the Enter key.
The parameters
may be used in any place in the batch file where a parameter would normally be used
as part of the DOS command
being run.
Markers are used within the batch file to signify
which parameter goes where. Markers are comprised of
a percent sign (%)
and
a single digit between 0 and 9 (that's ten markers in use
at
any one time;
remember,
zero is
a number).
As an example:
Assume that a batch file named REPEAT.BAT is on the current drive. This file contains two
commands: "ECHO OFF"
which stops DOS from showing commands and "ECHO %1 %3" where
the ECHO command can show
messages on the
screen. If, at the DOS prompt you typed "REPEAT Red Blue Green" your screen would show "Red Green" as
shown in the screen capture:
In this simple example, three
parameters were
passed to the
batch file and were placed into the ECHO command in the order received. Only the first and third are shown as only
those were referenced
in the batch file.
The parameters and
markers
were related
as
follows...
• %1 is marker 1 and,
in this example,
represents "Red", the first
parameter;
• %3 is marker 3 and,
in this example,
represents "Green",
the
third parameter;
• %2 would be marker 2 but, in this example, is not present so "Blue", the second parameter,
is ignored.
Note: Marker zero is assigned the name of the batch file in the form you typed it in (i.e., all caps, all
lower case, or a mixture).
In addition to the normal DOS commands, batch files have their own subcommand structure. Following are the subcommands
in the order we will discuss them:
• ECHO: Turns command
display on/off or may display a message.
• REM: Displays
a message on
the screen.
• PAUSE: Temporarily stops
the
batch file execution.
• GOTO: Jumps to
a labeled
set of commands in
the batch
file.
• IF: Permits conditional
operation of any command.
• SHIFT: Reassigns the relationship of parameters to
markers.
• FOR..IN..DO: Allows iteration
subject
to defined conditions.
• CALL: Runs
another batch file then
returns
to first.
ECHO
You have seen one facet of ECHO already: it can send a message to the screen. More
importantly, it can help clear the clutter on the screen when a batch file executes. Normally, the batch file commands would show on the screen as if you were typing
them. This can get distracting. If you
want to suppress the command
echoing type:
ECHO OFF
To
restart echoing,
type: ECHO ON
When ECHO is off no part of the actual DOS commands in the batch file will show
on the
screen. To display a message put
it after the ECHO command:
ECHO Message
As you will see, the REMark command also displays messages; but NOT if
ECHO
is
off! Use ECHO
if you want
the
message to show no
mater what.
REMark
REMark can be used to send messages to the screen or simply to document some part of
your batch file's operation.
Use them extensively
in
long batch files. The computer operator (it won't always be you) wants to know what is happening
and, over time, you might forget what a complicated set of
commands really does.
The format is:
REM Message
REMarks can be up to 123 characters long, although you usually won't want to go over the screen width
so you can control
the
display.
An undocumented, variation of this command is the period. In DOS 2.x, if
a line in a batch file starts with one or more periods (.) it is treated as a remark. It is dangerous to use this however since in DOS 3.x and later that
same line would
be treated as
the path to
a command!
PAUSE
The
last "simple" command is PAUSE.
Its basic function is to stop the execution of the
batch file until you press a key. This can allow you to perform a necessary
task; like perhaps changing a disk or verifying that a particular disk configuration is in place in order to avoid errors
as the remaining parts
of the batch
file are executed.
In early DOS versions PAUSE would optionally display a message. It does not now. In
order to
display a message you
have to couple PAUSE
with
the
ECHO command.
The
format in
use now would require:
ECHO Message
PAUSE
The message will
show, followed by the DOS message: Strike a key when ready... (in early DOS versions)
Press any key to continue...
(in
later DOS versions)
GOTO
The format
for this command
is:
GOTO LABEL
where LABEL is a line in your batch file that starts with a colon (:) followed by up to an eight
character name (actually, you can type any number of characters, but DOS only recognizes the first
eight).
Want to create an endless loop? GOTO
gives you an easy way. Here is
one example:
:START
REM...This is
being typed by an endless
loop. GOTO START
When executed,
this
file will continue to
print the
endless loop
line and
the GOTO
command
until you tap
Control-Break.
Use this subcommand
to transfer control
in your batch files.
If you want to terminate any batch file before it is complete, issue the break command
[Control-Break].
Interim Review
You have now seen the simple stuff...Let's see how much of it stuck. Following are a few
true/false questions. Think of the answer then look below to
see
if you were right.
Questions:
1. The
file AUTOEXEC.BAT
must be in the root directory of the boot disk.
2.
Batch files
can
execute a variety of subcommands in
addition
to the standard
DOS commands.
3.
Parameters are designated
as %0
through
%9.
4. When DOS finds a batch subcommand that is improperly phrased, it stops execution of the file and
shows Syntax error.
5.
You may interrupt a
batch command
by
pressing Control-Home.
6. When you type Control-Break to stop a batch file, DOS will ask you if you want to terminate. If you say No the current command
will
be ignored but the rest will be processed.
7. The batch filename is substituted for marker %0.8. REMark subcommands display a message
regardless
of the the condition of
ECHO.
9.
PAUSE causes the batch
file to
temporarily stop
and wait for you to
press a key.
Answers:
1. True, AUTOEXEC.BAT executes automatically when DOS boots so it must be in the root. (A
trick question as
it assumes
knowledge from prior tutorials. )
2.
True, you've seen some, with more to come.
3. False, those are markers. A parameter is information you type in on the command line that is
substituted for a marker when commands
are executed.
4.
True,
we
didn't talk about that specifically, but that's what
happens.
5. False,
the
correct command is
Control-Break.
6.
True,
revealing another little quirk
of batch file processing.
7.
True,
but there is a command you
can
use to change that as
we'll see later.
8. False, REM only shows its message if ECHO is ON. If ECHO is OFF, only ECHO puts a message to
the
screen.
9.
True.
That's enough. You should now understand the batch file subcommands you are likely to need
most often.
Let's move on to
the
rest of the subcommands that allow you
to program
within
a batch file. Subcommands in this section are generally used to create batch programs. As such, they are a bit more complex than the simply ones studied
on the last page.
IF
The IF subcommand
allows you
to make decisions within your batch file. Its syntax is:
IF Condition Command where,
Command
= Any legal
DOS command
or batch file subcommand
Condition =
One of three tests that yield
true or false:
1.
The ERRORLEVEL of a program.
2.
Two strings
are equivalent.
3.
A file exists
in the current
directory.
Unlike programming languages, which allow many logical tests
in an IF statement,
the
batch
IF statement is
limited to only the three above.
Condition 1: ERRORLEVEL is a number that indicates to DOS whether the last program run
was successful.
A zero (0) indicates a good run, anything above zero indicates an error condition. (Only
DOS commands
BACKUP and RESTORE have an
exit code.)
You can create small programs to capture the keyboard output and report it as an error level
(see Batch
Sample #3
later).
Condition 2: String comparison is
indicated by double equal signs: String1 == String2
compares the two strings.
This comparison is
often used with parameters
and
markers to check
for a particular entry. For example,
IF %1 == 40 MODE C40
checks parameter one for 40 and,
if
found, changes the display to
40-columns wide.
Condition 3: The logical test
checking for a file has
the
format: EXIST
d:Filename
You can use this test to check and see if
a DOS disk is in the active drive
(as one example). Another use might be to check for a particular file to see if
the
user has a valid disk in the drive.
Pathnames
are
NOT allowed.
Password
Example
The following batch file can be used to establish a password for running a program. The
batch file is named
START.BAT and calls the program named
WP.COM.
ECHO OFF
IF %1==XYZ GOTO GOOD
ECHO BAD PASSWORD...ENDING GOTO END
:GOOD
ECHO YOU'RE OK...STARTING WP
:END
Below you'll see the response of the computer to various
commands... First
the
bad password. At
the
prompt type START
ABC.
A>START ABC A>ECHO OFF
BAD PASSWORD...ENDING A>_
Now
use the correct
password.
Type the correct command
at the prompt.
A>START XYZ A>ECHO OFF
YOU'RE OK...STARTING
At this point
the
WP program
starts. You
don't
see
the command because echo is
off.
SHIFT
The limit of 10 parameters
for a batch file can be raised
through
use of the
SHIFT
command.
The syntax is
the
single word:
When that subcommand is encountered, all parameter/marker pairings are shifted one to the
left. Whatever was assigned to %0 is lost, the contents of %1 are moved to %0, %2 moves to %1 ...
%9 moves
to %8
and a new parameter from the command
line
is moved into
%9.
While this brings in a new parameter, all have shifted and you must anticipate the effect on your
batch file "program."
The effect of
SHIFT:
Remember, this command seems very simple, but its effects are far ranging and the logical consequence of mismatching parameters
and markers
and be disastrous!
FOR..IN..DO
This command is similar to the programmer's FOR..NEXT loop in that a particular action
can be repeated a given number of times. The
syntax (which may look a bit complicated) is:
FOR %%Variable IN (Set) DO
Command
%%Variable is one-letter with the mandatory %% before it. Two percentage signs are used
so this variable won't
be confused
with
a marker.
(Set) is one or more filenames or commands you want %%Variable to assume while the
command is being executed. Use a space between entries, and pathnames are allowed. Don't forget
the
parenthesis around the set.
Wildcards may be used
within (Set) if you are using
filenames.
Command is the particular DOS command or batch subcommand you want to have performed.
Usually one or more of these commands will contain the %%Variable in it. If (Set) contains DOS commands,
only
%%Variable is used.
In effect, what this subcommand does is cause %%Variable to be an index into the (Set) for use
by Command.
An example:
Problem: Compare all files on the disk in drive A: with those on the disk in drive B: and report
those that match.
Answer: The following two-line batch
file run
from
the
A: drive will do that task:
ECHO OFF
FOR %%Z IN (*.*) DO IF EXIST B:%%Z ECHO %%Z is
on A: and B:
Let's see how...
The first line turns command display off to clear the clutter.
The second line is executed as many times as there are files on the disk in A: [the set (*.*)
assures this]. Each of those filenames are assigned to %%Z in turn and then checked for presence
on drive B: with the EXIST logical statement. If EXIST is true, then the message at the end of the
IF
subcommand is sent to the screen, otherwise nothing is printed and the next file on drive A: is assigned and checked.
The following will diagram
this
process...
Files on drive A:
COMMAND.COM FILE.ONE
FILE.TWO
Files on drive B:
COMMAND.COM FILE.ONE
FILE.LTR
The batch
subcommand we are investigating is:
FOR %%Z IN (*.*) DO IF EXIST B:%%Z ECHO %%Z is
on A: and B:
Each filename on A: is substituted in the IF subcommand and then executed. To get the
same effect you would have to type:
IF EXIST B:COMMAND.COM ECHO COMMAND.COM is
on A: and B: IF EXIST B:FILE.ONE ECHO FILE.ONE is
on A: and B:
IF EXIST B:FILE.TWO ECHO FILE.TWO is on A: and B:
In the case
of the
example
above, the first two would have
a positive response and the
last
would
not print anything. Study it carefully before going on!
Another example: Files
on drive A:
COMMAND.COM FILE.ONE
FILE.TWO
Files on drive B:
COMMAND.COM FILE.ONE FILE.LTR
OK, told you to
study the example. Let's see if you remember. What
is the one line batch file
command to
find
and report out all files
starting with
an "F" on
drive A:?
FOR %%Z IN (A:F*.*) DO ECHO File %%Z is on drive A:
In this case you see that the A: disk is checked for any file starting with the letter "F" and that name is substituted
in the variable %%Z. The appropriate message is
then
printed.
This is
not an easy concept. It will require some study and practice to master. Let's now look at
using DOS commands in
(Set).
The (Set) can contain DOS commands instead of filenames and these commands will then
be executed in sequence (to include running
large programs under the control of the FOR..IN..DO
loop).
Let's say you want to
sequentially:
• Clear the screen,
• Show the DOS version
number,
• then Show a disk directory with
pause on.
You could
do all that in
a one
line batch
file with
the
following command in
it:
FOR %%T IN (CLS Ver Dir/P) DO
%%T
When using
DOS
commands in (Set) you must use the space as a delimiter and cannot have the asterisk (*) or question mark (?) in any
command. Use a colon (:) instead of a space when passing parameters to programs (i.e., DBASE:FILE instead of DBASE FILE). [The colon trick does not always
work; you
have
to experiment.]
It is possible to issue the FOR..IN..DO command at the DOS prompt by dropping one of the percentage signs
(%) on the variable.
CALL
Sometimes it's handy to be able to run one batch file from another. Until DOS 3.3 you had
to resort to tricks to do that; without the tricks when you called a second batch file from a first then control
would
transfer to
the
second and you'd never get
back
to the first.
The command: CALL d:path\FILENAME parameters
can be used in DOS versions 3.3 and later to start a second batch file from a parent and then return
to the parent
after the second
finishes. Note: Do
not use pipes or redirection
on the second file.
The FILENAME is the name of the second batch file; the parameters are any options that
the
second file requires to properly run. When the second batch file terminates, control is returned to
the
first batch
file on the line following the CALL command.
You can simulate CALL
in DOS versions lower than 3.3 by using:
COMMAND /C d:path\FILENAME parameters
@
In DOS 3.3 and later you can selectively cause lines in a batch file from being
displayed. To
cause this, place an "@" sign in
front of the line in question.
One use of this would be to suppress showing the "ECHO OFF" command which is the starting command of many
batch files. Until the ECHO OFF command is actually
executed, ECHO
is
ON and the command shows. To stop even this from showing
make the first command: @ECHO
OFF.
If you need to use the "@" feature with a command that already starts with @ (e.g.,
@WIP.EXE) then use a double @
(e.g., @@WIP) in the batch
file (this should be rare). Below
are some simple batch
file examples to
whet your appetite.
26.1
AUTOEXEC.BAT
AUTOEXEC.BAT is a special batch file name that, if found in the root directory of the boot
disk, will automatically run before control of
the computer is turned
over to you.
You might want to always load particular files on starting the computer and the commands
to do this would
be in
AUTOEXEC.BAT.
Typically, the AUTOEXEC.BAT file is used to set the system up to your particular needs.
This
includes setting
the
PATH to define where DOS will look for commands, defining various variables
in the DOS environment
and setting the PROMPT
to look
like you want
it to.
If you want to terminate the AUTOEXEC.BAT file (or any other batch file) before it is complete,
issue the break command
[Control-Break].
Path C:\DOS;C:\;C:\BAT;C:\UTILITY; Prompt $p$g
Set TEMP=C:\Temp C:\Utility\NumLock – CD\
CLS
Type C:\Bat\Menu.TXT
This file sets the PATH, defines a prompt and a temporary directory, runs a utility program and
then
clears
the
screen and types a menu.
Batch Sample #1
Here is
a
sample
batch file you
might
use
to periodically back
up
and clear
a
word
processing data disk. It assumes that word processing backup files are named with extension .BAK,
you don't want them, and they are on the disk in drive B:. The batch file is called BAK.BAT and is
also
on the word processing data disk in
drive B:. Start
it by typing B:BAK.
ECHO * * *
Word processing cleanup * * * ECHO Put backup disk in
drive A:
PAUSE
ERASE B:*.BAK COPY B:*.* A: DEL A:BAK.BAT
ECHO
Backup is
complete. Label your disk.
The first line turns screen echo off. The next line clears the screen. A label is then displayed
with instructions on where
to
place the backup disk. A
keypress needed to continue, then all .BAK
files are erased and all files on drive B: are copied to A:. The batch file is then deleted from A: and
a termination
message shown.
Your situation might be different and you may not want to delete .BAK files first, but this should
give you
an idea of what you
can
do.
Batch Sample #2
Suppose you have a phone list in a file named FONE on your disk. There is a DOS utility
called FIND which allows you to search files for specific text strings. The general format for using
FIND is:
FIND "text" filename.
Instead
of typing a complicated
command each time, create a batch
file called
LOOKUP.BAT as follows:
This file is called up by typing LOOKUP NAME at the system prompt. Assuming
that you
have typed
the
name in
all
caps, you might see a response like:
C> LOOKUP JONES
JONES Tom (805) 555-1212 Tom owes me $50
Clever use of DOS will save you
money!
Batch Sample #3
Call this file MENU.BAT. It demonstrates branching. See below for creation of GETKEY
which stops the computer, waits for a keystroke and returns its ASCII value as a program error level. (The ASCII value of 1
is 49, 2 is 50 and 3 is 51.)
An IF ERRORLEVEL test is true if the error level tested is less than or equal to the actual error
level.
Therefore, such
tests
have to be in
reverse order or the first
will
always be true.
:START CLS
ECHO --------------------
ECHO 1 – Wordprocessing
ECHO 2 – Spreadsheet ECHO
3 - Exit menu to DOS
ECHO --------------------
:QUERY
ECHO 1, 2, or 3? GETKEY
IF ERRORLEVEL 52 GOTO QUERY IF ERRORLEVEL 51 GOTO L3
IF ERRORLEVEL 50 GOTO L2
IF ERRORLEVEL 49 GOTO L1
GOTO QUERY
:L1
Commands
necessary to call up
word
processor
GOTO START
:L2
Commands
necessary to call up
spreadsheet
GOTO START
:L3
CLS
GETKEY.COM
GETKEY.COM is a small file that you need to create to allow the example above to work.
If you are not comfortable with the procedure outlined below DO NOT DO IT. The
program
DEBUG can
be
dangerous when used
improperly.
DEBUG comes
with
most versions of DOS.
You type everything highlighted:
C:\> DEBUG
-E 100 B4
00 CD 16 B4 4C CD 21
-N GETKEY.COM
-R CX
CX 0000
:8
-W
Writing 0008 bytes
-Q
The DEBUG command starts the DEBUG program. The prompt for that program is a
hyphen. The "E"
command enters data and the "N"
command names a file. The "R"
command finds
out what's in register CX and then enters a new value (the number of commands in this case). The
"W" command tells DEBUG to write the file and "Q" quits the DEBUG program and drops you back
to the DOS prompt.
You should now have the file GETKEY.COM on the default drive. Try it in a batch file like the one above.
The limits
to the uses
of batch files
are found only in your imagination.
One batch file can call another, but the original file will
loose control
of the computer, so don't expect the first batch file to do anything of use after a second is called. DOS 3.3 introduced the
CALL command to get
around
this
limitation.
Some of the commands will even work directly at the DOS prompt. A batch file might not be
necessary. The FOR..IN..DO command, for
example, can be
used outside of a batch file if you use only one percentage sign (%) to
designate the variable instead of
two.
If a batch file contains a syntax error in any of its commands, the file will stop execution at that
point and you will be returned to
the
DOS prompt.
Finally, DOS "remembers" the disk that contains the batch file and the drive it was in. If you
removed the original
disk,
DOS
will ask you
to replace it before going on.
A summary:
•
CALL Filename
• Calls a second batch file from
within a parent.
• ECHO ON
-or- ECHO OFF -or- ECHO <Message>
• Turns command display on or off, or
displays a message to
the
screen.
• FOR %%Variable IN (Set) DO
Command
• Allows use
of a single batch command
for
several
different
variables.
• GOTO Label
• Jumps to locations
within a batch file.
• IF Condition Command
• Permits conditional execution of
commands, and
• where Condition is
o ERRORLEVEL #
o String1 == String2 o EXIST Filename
•
PAUSE Message
• Halts execution
until the user presses a key.
• REM Message
• Displays a message to
the screen
if
ECHO is on.
• SHIFT
Shifts command
line
parameters
to the left by one.
• @
Turns display off for a single command
No comments:
Post a Comment