Batch files
With batch files, which are also called batch programs or scripts, you can simplify routine or repetitive tasks. A batch file is an unformatted text file that contains one or more commands and has a .bat or .cmd file name extension. When you type the file name at the command prompt, Cmd.exe runs the commands sequentially as they appear in the file.
You can include any command in a batch file. Certain commands, such as for, goto, and if, enable you to do conditional processing of the commands in the batch file. For example, the if command carries out a command based on the results of a condition. Other commands allow you to control input and output and call other batch files.
The standard error codes that most applications return are 0 if no error occurred and 1 (or higher value) if an error occurred. Please refer to your application help documentation to determine the meaning of specific error codes.
For more information about batch file operations, see the following topics:
- Using batch parameters
- Using filters
- Using command redirection operators
For more information about commands that you can use in batch files, click a command:
- Call
- Echo
- Endlocal
- For
- Goto
- If
- Pause
- Rem
- Setlocal
- Shift
1. Call
Calls one batch program from another without stopping the parent batch program. The call command accepts labels as the target of the call. Call has no effect at the command-line when used outside of a script or batch file.
[ Drive : ][ Path ] FileName : Specifies the location and name of the batch program you want to call. The FileName parameter must have a .bat or .cmd extension.
Syntax
call [[Drive:][Path] FileName [BatchParameters]] [:label [arguments]]BatchParameters : Specifies any command-line information required by the batch program, including command-line options, file names, batch parameters (that is, %0 through %9), or variables (for example, %baud%).
: label : Specifies the label to which you want a batch program control to jump. By using call with this parameter, you create a new batch file context and pass control to the statement after the specified label. The first time the end of the batch file is encountered (that is, after jumping to the label), control returns to the statement after the call statement. The second time the end of the batch file is encountered, the batch script is exited. For a description of the goto :eof extension that allows you to return from a batch script, see Related Topics.
arguments : Specifies any command-line information that you pass to the new instance of the batch program that begins at :label, including command-line options, file names, batch parameters (that is, %1 through %9), or variables (for example, %baud%).
/? : Displays help at the command prompt.
2. Echo
Turns the command-echoing feature on or off, or displays a message. Used without parameters, echo displays the current echo setting.
{ on | off } : Specifies whether to turn the command-echoing feature on or off.
Syntax
echo [{on|off}] [message]message : Specifies text you want to display on the screen.
/? : Displays help at the command prompt.
- The echo message command is useful when echo is turned off. To display a message that is several lines long without displaying other commands, you can include several echo message commands after the echo off command in your batch program.
- If you use echo off, the command prompt does not appear on your screen. To display the command prompt, type echo on.
- To prevent echoing of a line, insert an at sign (@) in front of a command in a batch program.
- To echo a blank line on the screen, type:
echo. - To display a pipe (|) or redirection character (< or >) when you are using echo, use a caret character immediately before the pipe or redirection character (for example, ^>, ^<, or ^| ). If you need to use the caret character (^), type two (^^).
echo off echo. echo This batch program echo formats and checks echo new disks echo.If you want to turn echo off and you do not want to echo the echo command, type an at sign (@) before the command as follows:
@echo off
You can use the if and echo commands on the same command line. For example:
if exist *.rpt echo The report has arrived.
Format | Meaning |
---|---|
Italic | Information that the user must supply |
Bold | Elements that the user must type exactly as shown |
Ellipsis (...) | Parameter that can be repeated several times in a command line |
Between brackets ([]) | Optional items |
Between braces ({}); choices separated by pipe (|). Example: {even|odd} | Set of choices from which the user must choose only one |
Courier font | Code or program output |
3. Endlocal
Ends localization of environment changes in a batch file, restoring environment variables to their values before the matching setlocal command.
/? : Displays help at the command prompt.
You can localize environment variables in a batch file. For example:
Syntax
endlocal/? : Displays help at the command prompt.
- You must use endlocal in a script or batch file. If you use endlocal outside of a script or batch file, it has no effect.
- There is an implicit endlocal command at the end of a batch file.
- With command extensions enabled (that is, the default), the endlocal command restores the state of command extensions (that is, enabled or disabled) to what it was before the matching setlocal command was executed. For more information about enabling and disabling command extensions, see cmd in Related Topics.
@echo off
rem This program starts the superapp batch program on the network,
rem directs the output to a file, and displays the file
rem in Notepad.
setlocal
path=g:\programs\superapp;%path%
call superapp>c:\superapp.out
endlocal
start notepad c:\superapp.out
4. For
Runs a specified command for each file in a set of files.
{ % variable | %% variable } : Required. Represents a replaceable parameter. Use %variable to carry out for from the command prompt. Use %%variable to carry out the for command within a batch file. Variables are case-sensitive and must be represented with an alpha value, such as %A, %B, or %C.
To use for in a batch file, use the following syntax:
Syntax
for {%variable|%%variable} in (set) do command [ CommandLineOptions]{ % variable | %% variable } : Required. Represents a replaceable parameter. Use %variable to carry out for from the command prompt. Use %%variable to carry out the for command within a batch file. Variables are case-sensitive and must be represented with an alpha value, such as %A, %B, or %C.
( set ) : Required. Specifies one or more files, directories, range of values, or text strings that you want to process with the specified command. The parentheses are required.
command : Required. Specifies the command that you want to carry out on each file, directory, range of values, or text string included in the specified (set).
CommandLineOptions : Specifies any command-line options that you want to use with the specified command.
/? : Displays help at the command prompt.
Remarks
- Using for
You can use the for command within a batch file or directly from the command prompt. - Using batch parameters
The following attributes apply to the for command:- The for command replaces %variable or %%variable with each text string in the specified set until the command processes all of the files.
- For variable names are case-sensitive, global, and no more than 52 total can be active at any one time.
- To avoid confusion with the batch parameters %0 through %9, you can use any character for variable except the numerals 0 through 9. For simple batch files, a single character such as %%f works.
- You can use multiple values for variable in complex batch files to distinguish different replaceable variables.
- Specifying a group of files
The set parameter can represent a single group of files or several groups of files. You can use wildcards (that is, * and ?) to specify a file set. The following are valid file sets:
(*.doc)
(*.doc *.txt *.me)
(jan*.doc jan*.rpt feb*.doc feb*.rpt)
(ar??1991.* ap??1991.*)
When you use the for command, the first value in set replaces %variable or %%variable, and then the specified command processes this value. This continues until all of the files (or groups of files) that correspond to the set value are processed. - Using the in and do keywords
In and do are not parameters, but you must use them with for. If you omit either of these keywords, an
error message appears. - Using additional forms of for
If command extensions are enabled (that is, the default), the following additional forms of for are supported:- Directories only
If set contains wildcards (* and ?), the specified command executes for each directory (instead of a set of files in a specified directory) that matches set. The syntax is:
for /D {%% | %}variable in (set) do command [CommandLineOptions] - Recursive
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, the current directory is assumed. If set is just a single period (.), it only enumerates the directory tree. The syntax is:
for /R [[Drive :]Path] {%% | %}variable in (set) do command [CommandLineOptions] - Iterating a range of values
Use an iterative variable to set the starting value (start#) and then step through a set range of values until the value exceeds the set ending value (end#). /L will execute the iterative by comparing start# with end#. If start# is less than end# the command will execute. When the iterative variable exceeds end# the command shell exists the loop. You can also use a negative step# to step through a range in decreasing values. For example, (1,1,5) generates the sequence 1 2 3 4 5 and (5,-1,1) generates the sequence (5 4 3 2 1). The syntax is:
for /L {%% | %}variable in (start#,step#,end#) do command [CommandLineOptions] - Iterating and file parsing
Use file parsing to process command output, strings and file content. Use iterative variables to define the content or strings you want to examine and use the various ParsingKeywords options to further modify the parsing. Use the ParsingKeywords token option to specify which tokens should be passed as iterator variables. Note that when used without the token option, /F will only examine the first token.
File parsing consists of reading the output, string or file content, breaking it up into individual lines of text and then parsing each line into zero or more tokens. The for loop is then called with the iterator variable value set to the token. By default, /F passes the first blank separated token from each line of each file. Blank lines are skipped. The different syntaxes are:
for /F ["ParsingKeywords"] {%% | %}variable in (filenameset) do command [CommandLineOptions]
for /F ["ParsingKeywords"] {%% | %}variable in ("LiteralString") do command [CommandLineOptions]
for /F ["ParsingKeywords"] {%% | %}variable in ('command') do command [CommandLineOptions]
The filenameset argument specifies one or more file names. Each file is opened, read and processed before going on to the next file in filenameset. To override the default parsing behavior, specify "ParsingKeywords". This is a quoted string that contains one or more keywords to specify different parsing options.
If you use the usebackq option, use one of the following syntaxes:
for /F ["usebackqParsingKeywords"] {%% | %}variable in ("filenameset") do command [CommandLineOptions]
for /F ["usebackqParsingKeywords"] {%% | %}variable in ('LiteralString') do command [CommandLineOptions]
for /F ["usebackqParsingKeywords"] {%% | %}variable in (`command`) do command [CommandLineOptions]
The following table lists the parsing keywords that you can use for ParsingKeywords.
Keyword Description eol=cSpecifies an end of line character (just one character).skip=nSpecifies the number of lines to skip at the beginning of the file.delims=xxxSpecifies a delimiter set. This replaces the default delimiter set of space and tab.tokens=x,y,m-nSpecifies which tokens from each line are to be passed to the for body for each iteration. As a result, additional variable names are allocated. The m-n form is a range, specifying the mth through the nth tokens. If the last character in the tokens= string is an asterisk (*), an additional variable is allocated and receives the remaining text on the line after the last token that is parsed.usebackqSpecifies that you can use quotation marks to quote file names in filenameset, a back quoted string is executed as a command, and a single quoted string is a literal string command. - Variable substitution
Substitution modifiers for for variable references have been enhanced. The following table lists
optional syntax (for any variable I).
Variable with modifier Description %~IExpands %I which removes any surrounding quotation marks ("").%~fIExpands %I to a fully qualified path name.%~dIExpands %I to a drive letter only.%~pIExpands %I to a path only.%~nIExpands %I to a file name only.%~xIExpands %I to a file extension only.%~sIExpands path to contain short names only.%~aIExpands %I to the file attributes of file.%~tIExpands %I to the date and time of file.%~zIExpands %I to the size of file.%~$PATH:ISearches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, this modifier expands to the empty string.
The following table lists modifier combinations that you can use to get compound results.
Variable with combined modifiers Description %~dpIExpands %I to a drive letter and path only.%~nxIExpands %I to a file name and extension only.%~fsIExpands %I to a full path name with short names only.%~dp$PATH:ISearches the directories listed in the PATH environment variable for %I and expands to the drive letter and path of the first one found.%~ftzaIExpands %I to an output line that is like dir.
By use uppercase variable names such as %I, you can make your code more readable and avoid confusion with the modifiers, which are not case-sensitive.
- Directories only
- Parsing a string
You can use the for /F parsing logic on an immediate string, by wrapping the filenameset between the parentheses in single quotation marks (that is,'filenameset'). Filenameset is treated as a single line of input from a file, and then it is parsed. - Parsing output
You can use the for /F command to parse the output of a command by making the filenameset between the parenthesis a back quoted string. It is treated as a command line, which is passed to a child Cmd.exe and the output is captured into memory and parsed as if it were a file.
To use for in a batch file, use the following syntax:
for %% variable in (set) do command [CommandLineOptions]
To display the contents of all the files in the current directory that have the extension .doc or .txt using the
replaceable variable %f, type:
for %f in (*.doc *.txt) do type %f
In the preceding example, each file that has the .doc or .txt extension in the current directory is substituted for the %f variable until the contents of every file are displayed. To use this command in a batch file, replace every occurrence of %f with %%f. Otherwise, the variable is ignored and an error message is displayed.
To parse a file, ignoring commented lines, type:
for /F "eol=; tokens=2,3* delims=," %i in (myfile.txt) do @echo %i %j %k
This command parses each line in Myfile.txt, ignoring lines that begin with a semicolon and passing the second and third token from each line to the FOR body (tokens are delimited by commas or spaces). The body of the FOR statement references %i to get the second token, %j to get the third token, and %k to get all of the remaining tokens. If the file names that you supply contain spaces, use quotation marks around the text (for example, "File Name"). To use quotation marks, you must use usebackq. Otherwise, the quotation marks are interpreted as defining a literal string to parse.
%i is explicitly declared in the FOR statement, and %j and %k are implicitly declared by using tokens=. You can specify up to 26 tokens using tokens=, provided that it does not cause an attempt to declare a variable higher than the letter 'z' or 'Z'.
To parse the output of a command by placing filenameset between the parentheses, type:
for /F "usebackq delims==" %i IN (`set`) DO @echo %i
This example enumerates the environment variable names in the current environment.
5. Goto
Within a batch program, directs Windows XP to a line identified by a label. When the label is found, it processes the commands that begin on the next line.
Syntax
goto labelParameters
label : Specifies the line in a batch program that you want to go to./? : Displays help at the command prompt.
Remarks
- Working with command extensions
If command extensions are enabled (that is, the default) and you use the goto command with a target label of :EOF, you transfer control to the end of the current batch script file and exit the batch script file without defining a label. When you use goto with the :EOF label, you must insert a colon before the label. For example:
goto :EOF
For a description of extensions to the call command that make this feature useful, see cmd in Related Topics. - Using valid label values
You can use spaces in the label parameter, but you cannot include other separators (for example, semicolons or equal signs). The goto command uses only the first eight characters of a label. For example, the following labels are equivalent and resolve to :hithere0:
:hithere0
:hithere01
:hithere02 - Matching label with the label in the batch program
The label value you specify must match a label in the batch program. The label within the batch program must begin with a colon (:). Windows XP 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, any commands on that line are ignored. If your batch program does not contain the label that you specify, the batch program stops and displays the following message:
Label not found - Using goto for conditional operations
You can use goto with other commands to perform conditional operations. For more information about using goto for conditional operations, see if in Related Topics.
echo off format a: /s if not errorlevel 1 goto end echo An error occurred during formatting. :end echo End of batch program.
6.If
Performs conditional processing in batch programs.Syntax
if [not] errorlevel number command [else expression]if [not] string1==string2 command [else expression]if [not] exist FileName command [else expression]If command extensions are enabled, use the following syntax:if [/i] string1 CompareOp string2 command [else expression]if cmdextversion number command [else expression]if defined variable command [else expression]Parameters
not : Specifies that the command should be carried out 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 should be carried 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 (for example, %1). You do not need to use quotation marks around literal strings.exist FileName : Specifies a true condition if FileName exists.CompareOp : Specifies a three-letter comparison operator. The following table lists valid values for CompareOp.
Operator Description EQU equal to NEQ not equal to LSS less than LEQ less than or equal to GTR greater than GEQ greater than or equal to/i : Forces string comparisons to ignore case. You can use /i on the string1==string2 form of if. These comparisons are generic, in that if both string1 and string2are both comprised of all numeric digits, the strings are converted to numbers and a numeric comparison is performed.cmdextversion number : Specifies a true condition only if the internal version number associated with the Command Extensions feature of Cmd.exe is equal to or greater than number. The first version is 1. It is incremented by one when significant enhancements are added to the command extensions. Thecmdextversionconditional is never true when command extensions are disabled (by default, command extensions are enabled).defined variable : Specifies a true condition if variable is defined.expression : Specifies a command-line command and any parameters to be passed to the command in an else clause./? : Displays help at the command prompt.Remarks
- If the condition specified in an if command is true, the command that follows the condition is carried out. If the condition is false, the command in the ifclause is ignored, and executes any command in the else clause, if one has been specified.
- When a program stops, it returns an exit code. You can use exit codes as conditions by using the errorlevel parameter.
- Using defined variable
If you use defined variable, the following three variables are added: %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 get the ERRORLEVEL value instead. The following example illustrates how you can use errorlevel after running a batch program:goto answer%errorlevel% :answer0 echo Program had return code 0 :answer1 echo Program had return code 1 goto end :end echo done!You can also use the CompareOp comparison operators as follows:
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 get the cmdcmdline 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 get the CMDEXTVERSION value instead.- Using the else clause
You must use the else clause on the same line as the command after the if. For example:IF EXIST filename. ( del filename. ) ELSE ( echo filename. missing. )The following code does not work because you must terminate the del command by a new line:
IF EXIST filename. del filename. ELSE echo filename. missingThe following code does not work because you must use the else clause on the same line as the end of the if command:
IF EXIST filename. del filename. ELSE echo filename. missingIf you want to format it all on a single line, use the following form of the original statement:
IF EXIST filename. (del filename.) ELSE echo filename. missingIf the file Product.dat cannot be found, the following message appears:if not exist product.dat echo Can't find data fileIf an error occurs during the formatting of the disk in drive A, the following example displays an error message::begin @echo off format a: /s if not errorlevel 1 goto end echo An error occurred during formatting. :end echo End of batch program.If no error occurs, the error message does not appear.You cannot use the if command to test directly for a directory, but the null (NUL) device does exist in every directory. As a result, you can test for the null device to determine whether a directory exists. The following example tests for the existence of a directory:if exist c:\mydir\nul goto process7. Pause
Suspends processing of a batch program and displays a message prompting the user to press any key to continue.Syntax
pauseParameters
/? : Displays help at the command prompt.Remarks
- When you run prompt command, the following message appears:
Press any key to continue . . .- If you press CTRL+C to stop a batch program, the following message appears:
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 thepause 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.To create a batch program that prompts the user to change disks in one of the drives, type:@echo off :begin copy a:*.* echo Please put a new disk into drive A pause goto beginIn 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, thepause 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.
8.Rem
Enables you to include comments (remarks) in a batch file or in your configuration files.Syntax
rem [comment]Parameters
comment : Specifies any string of characters you want to include as a comment./? : Displays help at the command prompt.The following example shows a batch file that uses remarks for both explanations and vertical spacing:
- Using the echo command to display comments
The rem command does not display comments on the screen. You must use the echo on 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. The blank lines are ignored when processing the batch program.@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
9. Setlocal
Starts localization of environment variables in a batch file. Localization continues until a matching endlocal command is encountered or the end of the batch file is reached.Syntax
setlocal {enableextensions | disableextensions} {enabledelayedexpansion | disabledelayedexpansion}enableextensions : Enables the command extensions until the matching endlocal command is encountered, regardless of the setting prior to the setlocalcommand.disableextensions : Disables the command extensions until the matching endlocal command is encountered, regardless of the setting prior to the setlocalcommand.enabledelayedexpansion : Enables the delayed environment variable expansion until the matching endlocal command is encountered, regardless of the setting prior to the setlocal command.disabledelayedexpansion : Disables the delayed environment variable expansion until the matching endlocal command is encountered, regardless of the setting prior to the setlocal command./? : Displays help at the command prompt.Remarks
You can localize environment variables in a batch file, as follows:
- Using setlocal
When you use setlocal outside of a script or batch file, it has no effect.- Changing environmental variables
Use setlocal to change environment variables when you run a batch file. Environment changes made after you run setlocal are local to the batch file. Cmd.exe restores previous settings when it either encounters an endlocal command or reaches the end of the batch file.- You can have more than one setlocal or endlocal command in a batch program (that is, nested commands).
- Testing for command extensions in batch files
The setlocal command sets the ERRORLEVEL variable. If you pass either {enableextensions | disableextensions} or {enabledelayedexpansion |disabledelayedexpansion}, the ERRORLEVEL variable is set to zero (0). Otherwise, it is set to one (1). You can use this in batch scripts to determine whether the extensions are available, for example:verify other 2>nul setlocal enableextensions if errorlevel 1 echo Unable to enable extensionsBecause cmd does not set the ERRORLEVEL variable when command extensions are disabled, the verify command initializes the ERRORLEVEL variable to a nonzero value when you use it with an invalid argument. Also, if you use the setlocal command with arguments {enableextensions | disableextensions} or {enabledelayedexpansion | disabledelayedexpansion} and it does not set the
ERRORLEVEL variable to one (1), command extensions are not available.
For more information about enabling and disabling command extensions, see cmd in Related Topics.rem *******Begin Comment************** rem This program starts the superapp batch program on the network, rem directs the output to a file, and displays the file rem in Notepad. rem *******End Comment************** @echo off setlocal path=g:\programs\superapp;%path% call superapp>c:\superapp.out endlocal start notepad c:\superapp.out
10.Shift
Changes the position of batch parameters in a batch file.Syntax
shiftParameters
noneRemarks
- Using the shift command-line option with command extensions
When command extensions are enabled (that is, the default), the shift command supports the /n command-line option, which tells the command to start shifting at the nth argument, where n can be a value from zero to eight. For example,SHIFT /2would 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 batch 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 batch parameters
You can also use the shift command to create a batch file that can accept more than 10 batch 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.- Using %* with shift
Shift has no affect on the %* batch parameter.- Shifting parameters back
There is no backward shift command. After you carry out the shift command, you cannot recover the first batch parameter (%0) that existed before the shift.The following batch file, Mycopy.bat, shows how to use shift with any number of batch parameters. It copies a list of files to a specific directory. The batch parameters are represented by the directory and file name arguments.@echo off rem MYCOPY.BAT copies any number of files rem to a directory. rem The command uses the following syntax: rem mycopy dir file1 file2 ... set todir=%1 :getfile shift if "%1"=="" goto end copy %1 %todir% goto getfile :end set todir= echo All done
No comments:
Post a Comment