This command reference is based largely on Microsoft's documentation provided with Windows 2000, but has been rewritten to increase its usefulness and make it easier to read.
[TABLE]
If you want to turn
echo off and
you do not want to echo the echo command
itself, include
an at sign (@) before the command, as follows: @echo
off
To echo a blank line on
the
screen, you can type echo and then a period
(echo.).
There must be no intervening space.
You can use the
if and echo
commands on the same command line, as follows:
if exist *.log echo The log file has
arrived.
To display a pipe (|)
or
redirection character (< or >) when using the
echo
command, use a caret character immediately before the
pipe or
redirection character (for example, ^>, ^<, or
^| ). If
you need to use the caret character itself (^), use
two in a row
(^^).
call
echo endlocal
for goto if
pause rem setlocal&n
To continue reading for free, register below or login
Requires Membership to View
To read more you must become a member of SearchEnterpriseDesktop.com
Ends localization of
environment
changes in a batch file, restoring environment
variables to
their values before the matching setlocal
command. There
is an implicit endlocal command at the end of
the batch
file.
endlocal
If command extensions are enabled (the default in
Windows 2000),
the endlocal command restores the
enabled/disabled state
of command extensions to what it was before the
matching setlocal
command was executed.
[TABLE]
call
echo endlocal
for goto if
pause rem setlocal
shift
% (variable)
FOR
Runs a specified
command for each
file in a set of files. You
can use the for command within a batch program
or
directly from the command prompt.
To use for in a
batch
program, use the following syntax:
for %%variable in
(set)do command
[command-parameters]
To use for from
the
command prompt, use the following syntax:
for %variable in (set)do command
[command-parameters]
Parameters
%%variable or %variable
Represents a replaceable
parameter. The for command replaces
%%variable
(or %variable) with each text string in
the
specified set until the command (specified in
the command-parameters)
processes all of the files. Use
%%variable to
carry out the for command within a batch
program. Use %variable
to carry out for from the command prompt.
Variable names
are case sensitive.
(set)
Specifies one or more
files or text
strings that you want to process with the specified
command. The
parentheses are required.
command
Specifies the command that you want to carry out on
each file
included in the specified set.
command-parameters
Specifies any parameters or switches that you want to
use with
the specified command (if the specified command uses
any
parameters or switches).
If command extensions
are enabled
(the default setting in Windows 2000), additional
forms of
the for command are supported.
If command extensions
are
enabled, the following additional forms of the
for
command are supported:
directories
only
for/D
[%% |
%]variable in (set)do command
[command-parameters]
If set contains
wildcards
(* and ?), specifies to match against directory names
instead of
file names.
Recursive
for/R [[drive :]path]
[%%
| %]variable in
(set)do command
[command-parameters]
Walks the directory tree rooted at
[drive:]path,
executing the for statement in each directory
of the
tree. If no directory is specified after /R
then the
current directory is assumed. If set is just a
single
period (.) character then it will only enumerate the
directory
tree.
Iterative
for/L [%% |
%]variable in (start,step,end)do command
[command-parameters]
The set is a sequence of numbers from start to end, by
step
amount. So (1,1,5) would generate the sequence 1 2 3 4
5 and
(5,-1,1) would generate the sequence (5 4 3 2
1).
File
parsing
for/F
["options"] [%%
| %]variable in
(filenameset)do command
[command-parameters]
for/F
["options"] [%%
| %]variable in ("literal
string")do command
[command-parameters]
for/F
["options"] [%%
| %]variable in
('command')do
command [command-parameters]
or, if usebackq option present:
for/F
["options"] [%%
| %]variable in
(filenameset)do command
[command-parameters]
for/F
["options"] [%%
| %]variable in ('literal
string')do command
[command-parameters]
for/F
["options"] [%%
| %]variable in
(`command`)do
command
[command-parameters]
The filenameset
parameter
specifies one or more file names. Each file is opened,
read and
processed before going on to the next file in
filenameset.
Processing consists of
reading in
the file, breaking it up into individual lines of text
and then
parsing each line into zero or more tokens. The body
of the for
loop is then called with the variable value(s) set to
the found
token string(s). By default, /F passes the
first blank
separated token from each line of each
file.
Blank lines are
skipped. You can
override the default parsing behavior by specifying
the optional
"options" parameter. This is a quoted string
which
contains one or more keywords to specify different
parsing
options. The keywords are:
[TABLE]
Variable
substitution
In addition, substitution modifiers for for
variable
references have been enhanced. You can now use the
following
optional syntax (for any variable
I):
[TABLE]
The modifiers can be
combined to
get compound results:
[TABLE]
[IMAGE] Note
call
echo endlocal
for goto if
pause rem setlocal
shift
% (variable)
GOTO
Directs
Windows 2000 to a
line in a batch program marked by a label you specify.
The
goto command directs Windows 2000 within a
batch
program to a line identified by a label. When
Windows 2000
finds the label, it processes the commands beginning
on the next
line.
goto
label
Parameter
label
Specifies the line in a batch program to which
Windows 2000
should go. If command extensions are enabled (the
default
setting in Windows 2000), goto changes as
follows: Using
the goto command with a target label of
:EOF
transfers control to the end of the current batch
script file,
exiting the batch script file without defining a
label.
Valid values for
label
The label parameter can include spaces but
cannot include
other separators, such as semicolons or equal signs.
When using goto
with the EOF label, you must insert a colon
before the
label, for example: goto
:EOF
Goto uses the first
eight
characters of each label
The goto command uses only the first eight
characters of
a label. Therefore, the labels ":hithere01"
and
":hithere02" are both equivalent to
":hithere0."
Matching the label
parameter
with the label in the batch program
The label value you specify on the goto command
line must
match a label in the batch program. The label within
the batch
program must begin with a colon.If your batch program
does not
contain the label that you specify, the batch program
stops and
Windows 2000 displays the following message:
Label
not found
Windows 2000
recognizes a
batch program line beginning with a colon (:) as a
label and
does not process it as a command. If a line begins
with a colon,
Windows 2000 ignores any commands on that
line.
Example
The following batch
program
formats a disk in drive A as a system disk. If the
operation is
successful, the goto command directs
Windows 2000 to
a label named "end."
[TABLE]
call
echo endlocal
for goto if
pause rem setlocal
shift
% (variable)
IF
Performs conditional
processing
in batch programs. If the condition specified in an
if
command is true, Windows 2000 carries out the
command that
follows the condition. If the condition is false,
Windows 2000
ignores the command in the if clause, and
executes any
command in the else clause, if one has been
specified.
if [not]
errorlevel number command
[else expression] if [not]
string1==string2
command [else expression] if [not] exist
filename
command [else
expression]
With command extensions
enabled:
if [/i]
string1 compare-op string2
command [else
expression] ifcmdextversion
number command
[else expression] ifdefined
variable command
[else expression]
Parameters
not
Specifies that
Windows 2000
should carry out the command only if the condition is
false.
errorlevel
number
Specifies a true condition only if the previous
program run
by Cmd.exe returned an exit code equal to or greater
than number.
command
Specifies the command that Windows 2000 should
carry out if
the preceding condition is met.
string1==string2
Specifies a true condition only if string1
and string2
are the same. These values can be literal strings or
batch
variables (%1, for example). Literal strings do
not need
quotation marks.
exist
filename
Specifies a true condition if filename
exists.
compare-op
one of the following three-letter comparison
operators:
[TABLE]
/i
The /i switch, when specified, forces string
comparisons
to ignore case. The /i switch can also be used
on the string1==string2
form of if. These comparisons are generic, in
that if
both string1 and string2 are both
comprised of all
numeric digits, then the strings are converted to
numbers and a
numeric comparison is performed.
cmdextversion
number
The cmdextversion conditional works just
like errorlevel,
except it is comparing against an internal version
number
associated with the Command Extensions feature of
Cmd.exe. The
first version is 1. It will be incremented by one when
significant enhancements are added to the command
extensions.
The cmdextversion conditional is never true
when command
cxtensions are disabled.
defined
variable
The defined conditional works just like
exist
except it takes an environment variable name and
returns true if
the environment variable is defined. Three variables
are added
with this conditional: %errorlevel%,
%cmdcmdline%,
and %cmdextversion%.
%errorlevel%
expands into
a string representation of the current value of
errorlevel,
provided that there is not already an environment
variable with
the name ERRORLEVEL, in which case you will get its
value
instead. After running a program, the following
illustrates errorlevel
use:
goto
answer%erorlevel%
:answer0
echo Program had return code 0
:answer1
echo Program had return code
1
You can also use the
comparison
operators listed above at
compare-op:
if %errorlevel%
LEQ 1 goto okay
%cmdcmdline%
expands into
the original command line passed to Cmd.exe prior to
any
processing by Cmd.exe, provided that there is not
already an
environment variable with the name cmdcmdline,
in which
case you will get its value instead.
%cmdextversion%
expands
into the a string representation of the current value
of cmdextversion,
provided that there is not already an environment
variable with
the name CMDEXTVERSION, in which case you will get its
value
instead.
expression
In an else clause, an expression
consists of a
Windows 2000 command and any parameters to be
passed to the
command.
Examples
Using if to verify
the
presence of a file
The following message appears if Windows 2000
cannot find
the file Product.dat:
if not exist product.dat echo Can't find data
file
Using if to post a
message
when an error occurs
The following example displays an error message if an
error
occurs during formatting of the disk in drive
A:
[TABLE]
If no error occurs, the
error
message is skipped.
Using if to verify
the
presence of a directory
The following example tests for the existence of a
directory.
The if command cannot be used to test directly
for a
directory, but the null (NUL) device does exist in
every
directory. Therefore, you can test for the null device
to
determine whether a directory exists.
Using the else
clause
The else clause must occur on the same line as
the
command after the if. For example:
The following does
not
work, because the del command must be
terminated by a
newline:
IF EXIST
filename. del filename. ELSE echo filename.
missing
The following does
not
work, because the else command must be on the
same line
as the end of the if command:
IF EXIST
filename. del filename.
ELSE echo filename.
missing
The following form of
the
original statement works, if you want to format it all
on a
single line:
IF EXIST
filename. (del filename.) ELSE echo filename.
missing
call
echo endlocal
for goto if
pause rem setlocal
shift
% (variable)
PAUSE
Suspends processing of
a batch
program and displays a message prompting the user to
press any
key to continue.
Prompting the user
to continue
the program Windows 2000 displays the following message
in response
to the pause command:
Press any key
to continue
. . .
Dividing a batch
file into
sections
If you press CTRL+C to stop a batch program,
Windows 2000
displays the following message: Terminate
batch job (Y/N)?
If you press Y (for yes) in response to this message,
the batch
program ends and control returns to the operating
system.
Therefore, you can insert the pause command
before a
section of the batch file you may not want to process.
While pause
suspends processing of the batch program, you can
press CTRL+C
and then Y to stop the batch program
Examples
Suppose you want a
batch program
to prompt the user to change disks in one of the
drives. To do
this, you might create the following file:
@echo off
:begin
copy a:*.*
echo Please put a new disk into drive A
pause
goto begin
In this example, all
the files on
the disk in drive A are copied to the current
directory. After
the displayed comment prompts you to place another
disk in drive
A, the pause command suspends processing so
that you can
change disks and then press any key to resume
processing. This
particular batch program runs in an endless loop. The
goto
BEGIN command sends the command interpreter to the
begin label
of the batch file. To stop this batch program, press
CTRL+C and
then Y.
call
echo endlocal
for goto if
pause rem setlocal
shift
% (variable)
REM
Enables you to include
comments
(remarks) in a batch file or in your configuration
files. This
is useful for documentation, and explaining what each
section of
your batch file does. (Trust me, you'll forget what
your
programming logic was a year from now.)
rem
[comment]
Parameter
comment
Specifies any string of characters you want to
include as a
comment
Using the echo
command to
display comments
The rem command does not display comments on
the screen.
You must use the echoon command in your
batch or
Config.nt file to display comments on the
screen.
Restrictions on
batch file
comments
You cannot use a redirection character "("
or
")" or pipe (|) in a batch file
comment.
Using rem to add
vertical
spacing
Although you can use rem without a comment to
add
vertical spacing to a batch file, you can also use
blank lines.
Windows 2000 ignores the blank lines when
processing the
batch program.
Examples
The following example shows a batch file that uses
remarks for
both explanations and vertical spacing:
@echo off
rem This batch program formats and checks new
disks.
rem It is named Checknew.bat.
rem
echo Insert new disk in drive B.
pause
format b: /v
chkdsk b:
Suppose you want to
include in
your Config.nt file an explanatory comment before the
prompt
command. To do this, add the following lines to
Config.nt:
rem Set prompt
to
indicate current directory
prompt $p$g
call
echo endlocal
for goto if
pause rem setlocal
shift
% (variable)
SETLOCAL
Allows you to create a
environment variable for use within a batch file. This
variable lasts until
a matching endlocal command is encountered, or
the until end of
the batch file.
setlocal
option
Parameter
option
When command extensions are enabled (the default in
Windows 2000),
the setlocal batch command accepts an optional
argument,
which can be either enableextensions or
disableextensions.
This enables or disables the command extensions until
the
matching endlocal command, regardless of their
setting
prior to the setlocal command.
The setlocal
command also
sets the errorlevel value when it is passed an
argument.
The errorlevel value is set to zero (0) if one
of the two
valid arguments is given and set to one (1)
otherwise.
call
echo endlocal
for goto if
pause rem setlocal
shift
% (variable)
SHIFT
Changes the position of
replaceable parameters in a batch file.
shift
When command extensions are enabled (the default
setting in
Windows 2000), the shift command supports
the /n
switch, which tells the command to start shifting at
the nth
argument, where n can be a value from zero to
eight.
For
example, SHIFT
/2 would
shift %3
to %2, %4 to %3, and so on, and
leave %0
and %1 unaffected
How the shift
command works
The shift command changes the values of the
replaceable
parameters %0 through %9, by copying
each
parameter into the previous one. In other words, the
value of %1
is copied to %0, the value of %2 is
copied to %1,
and so on. This is useful for writing a batch file
that performs
the same operation on any number of
parameters.
Working with more
than 10
command-line parameters
You can also use the shift command to create a
batch file
that can accept more than 10 parameters. If you
specify more
than 10 parameters on the command line, those that
appear after
the tenth (%9) will be shifted one at a time
into %9.
Shifting parameters
back
There is no backward shift command. After you
carry out
the shift command, you cannot recover the first
parameter
(%0) that existed before the shift.
Example The following batch file, testcopy.bat, shows how
to use the
shift command with any number of parameters. It
copies a
list of files to a specific directory. The parameters
are the
directory name followed by any number of file
names.
[TABLE]
call
echo endlocal
for goto if
pause rem setlocal
shift
% (variable)
%
(variable)
A variable is a
replaceable
parameter. The parameters %0 and %1 to %9 can be
placed anywhere
within a batch file. When the batch file is run, %0 is
replaced
by the name of the batch file, and the argument
variables %1 to
%9 are replaced by the corresponding parameters
entered on the
command line.
For example, to copy
the contents
of one folder to another, you would add the following
statement
in your batch file:
xcopy %1\*.*
%2
When you run the file,
you would
type the following:
mybatch.bat
C:\afolder D:\bfolder.
The effect is the same
as if you
had written xcopy C:\afolder \*.* D:\bfolder in
the batch
file.
The % parameter expands
the batch
script argument variables (%0, %1, ..., %9) as
follows:
%* in a batch
script is a
wildcard reference to all the arguments. For
individual argument
variables, the expansion options are explained in the
following
tables.
[TABLE]
The modifiers can be
combined to
get compound results:
[TABLE]
In the above examples
%1 and PATH
can be replaced by other valid values. The %~ syntax
must be
terminated by a valid argument number. The %~
modifiers may not
be used with %*.
call
echo endlocal
for goto if
pause rem setlocal
shift
% (variable)
Rate this Tip
To rate tips, you must be a member of SearchEnterpriseDesktop.com. Register now
to start rating these tips. Log in if you are already a member.
DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.
TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.