What Is a Batch File?

Batch processing, as its name implies, is batch processing. A batch file is a text file with the extension .bat or .cmd. It contains one or more commands and is interpreted by the command interpreter built into DOS or Windows.

Batch processing, as its name implies, is batch processing. A batch file is a text file with the extension .bat or .cmd. It contains one or more commands and is interpreted by the command interpreter built into DOS or Windows.
Chinese name
Batch file
Foreign name
BATCH
Common suffix
· Bat or · cmd
Operating platform
DOS or Windows
Features
Plain text file
Function
Simplify routine or repetitive tasks
Nature
DOS commands are arranged in order
How to call
CMD
Advanced command
if, choice, for

Batch file basic information

Batch files are plain text files. Type the name of the batch file at the command prompt, or double-click the batch file, and the system will call Cmd.exe to run them one by one in the order in which the commands in the file appear. Use batch files (also known as batch programs or scripts) to simplify daily or repetitive tasks.
The essence of batch processing is a collection of DOS commands arranged in a certain order.
Batch processing, also known as batch script, is translated into BATCH in English. The first three letters of the batch file suffix BAT are taken. Its composition has no fixed format, as long as it adheres to the following: each line can be regarded as a command, and each command can contain multiple subcommands, which are executed from the first line until the end of the last line. It's DOS. Batch processing has a very distinctive feature: easy to use, flexible, powerful, and highly automated.
For example, when starting wps software, it must be executed every time
C: \> cd wps
C: \ WPS> spdos
C: \ WPS> py
C: \ WPS> wbx
C: \ WPS> wps
If you do this every time before using WPS, it is more tedious.
If there is a way, just write a batch file and all the commands just executed will be executed automatically, which will simplify the work and bring convenience.
In addition, the computer will look for the batch file autoexec.bat every time it is started, so that it can execute some commands that must be executed every time it is turned on, such as setting the path, loading the mouse driver mouse, and disk acceleration smartdrv. Really automated.
Echo, @, call, pause, and rem are the most commonly used commands for batch files. We will start with them. echo means display the characters after this command
echo off means that all commands run after this statement do not show the command line itself
@ Is similar to echo off, but it is added to the front of other command lines, which means that the command line itself is not displayed at runtime.
call call another batch file (if another batch file is directly called, subsequent commands of the current file will not be executed after executing that command)
pause Running this sentence will pause and display Press any key to continue ... Wait for the user to press any key to continue
rem means that the character after this command is an interpreted line, it is not executed, but it is used for future searches.
Example: Edit the a.bat file with edit, enter the following content and save it as c: \ a.bat. After executing the batch file, it can be realized: write all files in the root directory into a.txt, start UCDOS, and enter WPS And other functions.

Batch file content

The contents of the batch file are: The file indicates:
echo off does not display the command line
dir c: \ *. *> a.txt write the c drive file list to a.txt
call c: \ ucdos \ ucdos.bat
echo hello shows "hello"
pause Pause, wait for the keypress to continue
rem using wps annotations will use wps
cd ucdos into the ucdos directory
wps use wps
The batch file can also use parameters like C language, which only needs a parameter indicator%.
% Indicates a parameter, which refers to a character string appended to the file name when the batch file is run. Variables can be from% 0 to% 9,% 0 represents the file name itself, and strings are represented in order from% 1 to% 9.
For example, C: The batch of processing files in the root directory is named f.bat and the content is format% 1
If C: \> fa: is executed, then format a:
Another example is C: The batch of processing files in the root directory is named t.bat, and the content is type% 1 type% 2
Then running C: \> t a.txt b.txt will sequentially display the contents of a.txt and b.txt files
if goto choice for is a more advanced command in batch files. If you are skilled in these, you are an expert in batch files.
if indicates that it will determine whether the specified conditions are met and thus decide to execute a different command. There are three formats:
1. if "parameter" == "string" Command to be executed
If the parameter is equal to the specified string, the condition is met and the command is run, otherwise the next sentence is run. (Note the two equal signs)
Such as if "% 1" == "a" format a:
2, if exist file name pending command
If there is a specified file, the condition is met and the command is run, otherwise the next sentence is run. If exist config.sysedit config.sys
3.if errorlevel number pending command
If the return code is equal to the specified number, the condition is met, the command is run, otherwise the next sentence is run. For example, if if errorlevel 2 goto x2 DOS program runs, it will return a number to DOS, which is called error code errorlevel or return code
Goto batch files run here will jump to the label specified by goto, generally used in conjunction with if. Such as:
goto end
: end
echo this is the end
The label is represented by a string, and the line where the label is located is not executed.
choice Use this command to let the user enter a character to run different commands. When using, you should add the / c: parameter. After c :, you should write a prompt for input characters without spaces. Its return code is 1234 ...
Such as: choice / c: dme defrag, mem, end
Will show
defrag, mem, end [D, M, E]?
For example, the content of test.bat is as follows:
@echo off
choice / c: dme defrag, mem, end
if errorlevel 3 goto defrag
if errorlevel 2 goto mem
if errotlevel 1 goto end
: defrag
c: \ dos \ defrag
goto end
: mem
mem
goto end
: end
echo good bye
After this file is run, defrag, mem, end [D, M, E] will be displayed. The user can select dme, and then the if statement will make a judgment. D means to execute the program labelled defrag, and m means to execute the program labeled mem Segment, e means to execute the program segment labeled end. At the end of each segment, the program jumps to the end label with goto end, and then the program displays good bye and the file ends.
for loop command, as long as the conditions are met, it will execute the same command multiple times.
Format FOR [%% f] in (set) DO [command]
As long as the parameter f is in the specified set, the condition is satisfied and the command is executed
If there is a line in a batch file:
for %% c in (* .bat * .txt) do type %% c
The meaning is that if the file ends with bat or txt, the content of the file is displayed.
autoexec.bat
DOS will automatically run the file autoexec.bat at startup. Generally, we load the necessary programs every time, such as: path (setting path), smartdrv (disk acceleration), mouse (mouse startup), mscdex (optical drive connection), doskey (keyboard management), set (set environment variables), etc.
If there is no such file in the root directory of the boot disk, the computer will ask the user to enter the date and time.
For example, a typical autoexec.bat reads as follows:
@echo off does not display the command line
prompt $ p $ g directory prompt before setting prompt
path c: \ dos; c: \; c: \ windows; c: \ ucdos; c: \ tools
lh c: \ dos \ doskey.com load keyboard management
lh c: \ mouse \ mouse.com Load mouse management
lh c: \ dos \ smartdrv.exe load disk acceleration management
lh c: \ dos \ mscdex / S / D: MSCD000 / M: 12 / V Load CD-ROM driver
set temp = c: \ temp

Common commands for batch files

Batch file description

echo, @, call, rem, pause, goto, set are the most commonly used commands for batch files.

echo Batch file echo command

Turns echoing on or off, or displays a message. Without any parameters, the echo command displays the current echo settings.
grammar
echo [{on | off}] [message]
Sample: @echo off / echo hello world
In practical applications, we will combine this command with a redirection symbol (also called a pipe symbol, generally using >>> ^) to implement input one.
Commands into specific files.

@ Batch file @command character

@ Is similar to the echo off function, but it is added to the front of other command lines, which means that the command line itself is not displayed at runtime.
For example:
-------------------------------------------------- --------------------------------------------------
@echo off
@echo Now initializing the program, please wait a minite ...
@format X: / q / u / autoset // The format command cannot use the / y parameter, but you can use autoset
// parameter, the effect is the same as y
-------------------------------------------------- --------------------------------------------------

call Batch file call command

The call command is used to call another batch program from one batch program without terminating the parent batch program. The call command prompts to accept a tag that is used as the target of the call. If you use the call command outside a script or batch file, it will not work on the command line.
grammar:
call [[Drive:] [Path] FileName [Bathparameters]] [: labe] [Arguments]]
parameter:
[Drive:] [Path] FileName
Specify the location and name of the batch program to be invoked. The FileName parameter must have a .bat or .cmd extension.
Batchparameters
Specify any command-line information required by the batch program, including command-line options, file names, batch parameters (that is, from% 0 to% 9), or variables (for example,% baud%).
: Label
Specifies the label to which the batch program will jump. Using the call command with this parameter, you can create a new batch file context and give control to the statement after the specified label. When the end of the processing file is encountered first (after jumping to the label), control is returned to the statement following the call statement. The second time the end of the batch file is encountered, a batch script is launched.
Arguments
For batch programs starting with: Label, specify all command-line information to pass to its new instance, including command-line options, file names, batch parameters (ie, from% 1 to% 9), or variables (for example,% baud %).
For example:
To run the checknew.bat program from another batch program, enter the following command in the parent batch program:
-------------------------------------------------- --------------------------------------------------
call checknew
-------------------------------------------------- --------------------------------------------------
If the parent batch program accepts two batch parameters and wants to pass them to checknew.bat, you can use the following command in the parent batch program:
-------------------------------------------------- --------------------------------------------------
call checknew% 1% 2
-------------------------------------------------- --------------------------------------------------

rem Batch file rem command

Comment command, similar to / * -------- * / in C language, it will not be executed, but only serves as a comment, easy for others to read
And modify it yourself later.
:: also has the function of rem
Rem Message
Sample: @Rem Here is the description.

pause Batch file pause command

Pause command. When you run the Pause command, the following message is displayed:
Press any key to continue... (Or: press any key to continue...)
Sample:
@echo off
: begin
copy G: *. * d: \ back
echo Please insert another disc ...
pause
goto begin
In this example, all files on the disk in drive G are copied to d: \ back. A comment is displayed prompting you to insert another disc
When the disc is placed in drive G, the pause command suspends the program so that you can replace the disc and then press any key to continue processing.

start Batch file start command

Calling external programs, all DOS commands and command line programs can be called by the start command.
For example: start calc.exe can open the calculator of Windows.
Common parameters:
Minimize the window at the beginning of MIN
SEPARATE starts 16-bit Windows programs in a separate space
HIGH Starts the application in the HIGH priority category
REALTIME starts the application in the REALTIME priority category
WAIT launches the application and waits for it to end
parameters These are the parameters passed to the command / program
When the executed application is a 32-bit GUI application, CMD.EXE returns to the command prompt without waiting for the application to terminate. If you order
Executed within the script, this new behavior does not occur.

goto Batch file goto command

Jump command. The program pointer jumps to the specified label, and execution of the batch program continues from the first command after the label.
grammar:
goto label
parameter:
label
Specify the lines in the batch program to go to.
Sample:
if (% 1) == {} goto noparms
if {% 2} == {} goto noparms (If you do nt understand if,% 1,% 2 here, skip first, there will be a detailed explanation later
. )
@Rem check parameters if null show usage
: noparms
echo Usage: monitor.bat ServerIP PortNumber
goto end
The name of the tag can be any name, but it is best to have a meaningful letter, preceded by the letter: used to indicate that the letter is a tag, goto
The command is based on this: to find the next step to jump there. It's best to have some explanations so that others seem to understand your intentions.

set Batch file set command

Display, set or delete variables.
Display variables: set or set s. The former displays all the variables and their values currently defined in the batch, and the latter displays all the variables and values starting with s.
Set variable: set aa = abcd This command can assign the value abcd to the variable aa. If the variable aa has been defined, the value of aa is modified to abcd; if aa has not been defined, this command can define a new variable aa, and at the same time assign the initial value abcd to the variable aa.
Delete a variable: set aa = This command deletes the variable aa. If the variable aa has been defined, delete the variable aa; if aa has not been defined, this command has no substantial meaning.
It should be noted that variables in batch processing are not type-dependent, and there is no need to distinguish int, float, char, etc. like variables in C language. For example, after executing set aa = 345, the value of the variable aa can be regarded as a number 345 or a string 345.
The set command has extended functions, such as being used for interactive input, string processing, and numerical calculation. It belongs to the category of advanced commands.

Batch file advanced commands

Batch file description

If, choice, for commands are more advanced commands in batch files

if Batch file if command

if command term performs conditional processing in a batch program
grammar:
if [not] errorlevel Number Command [else Expression]
if [not] Strting == String2 Command [else Expression]
if [not] exist FileName Command [else Expression}
If command extensions are enabled, you can use the following syntax:
if [/ i] String1 Compare0p String2 command [else Expression]
if cmdextversion Nuber Command [else Expression]
parameter:
not
Specifies that the command will be executed only if the condition is false
errorlevel Number
A true condition can only be specified when the previous program run by cmd.exe returned an exit code equal to or greater than Number.
Command
Specifies a command to be executed only if the previous conditions are met.
String1 == String2
You can specify a true condition only when String and String2 are the same. These values can be literal strings or batch variables (for example,% 1). For literal strings, no question mark is required.
exist FileName
If FileName exists, specify a true condition.
Compareop
Specify a 3-letter comparison operator. Table 1 lists the valid values of Compareop.
Operator
description
Operator
description
EQU
equal
LEQ
less than or equal to
NEQ
not equal to
GTR
more than the
LSS
Less than
GEQ
greater than or equal to
/ i
Force string comparison to ignore case. You can use / i on the String1 == String2 cell of if. These comparisons are general. Because if String1 and String2 all consist of numbers, the strings will be converted to numbers and comparisons will be performed.
cmdxtversion Number
A true condition is specified only if the build number associated with the "command extension" function of cmd.exe is equal to or greater than Number. The first version is 1. When the function of the command extension is greatly enhanced, add 1 to this number. When command extension is disabled (command extension is enabled by default), the cmdextversion condition is not true.
defined Variable
If Variable is defined, the specified condition is true.
Expression
Specifies the command line command and any parameters to be passed in the else clause.
For example:
Example 1: To display a message that the data file cannot be found when the file product.dat cannot be found, enter:
if not exist product .dat echo Cannot find data file
Example 2: If an error occurs during formatting the disk in drive A, the following command will display 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 errors occur, no error message appears

choice Batch file choice command

Using the choice command, in a batch program, the user can choose from a set of option keys by displaying a prompt message and pausing the batch program.
grammar:
choice [/ c [Choices]] [/ n] [/ cs] [/ t Timeout / d Choice] [/ m Text]
parameter:
/ c Choices
Specify a user option key. When displayed, option keys are separated by commas and appear in square brackets ([]), followed by question marks. If "/ c Choices" is not specified, the Choice display uses [Y, N] by default.
/ n
Hide user option keys. If you use this command-line option, the message body appears before the prompt, and the option is still enabled.
/ cs
Specifies that user option keys must be case sensitive. User option keys are not case sensitive by default.
/ t Timeout / d Choice
Specifies that choice pauses the specified number of seconds before defaulting to the specified key. Table 2 describes the values of the / t command line options.
value
description
Timeout
The number of seconds to pause. Acceptable values are from 0 to 9 999. If 0 is used, choice does not pause until it defaults to the specified key
/ d Choice
Specify the default selection after Timeout seconds. The characters used must be in the selection set specified by / c Choice. If you use this command-line option, you must also specify / t Timeout
Specifies the text to be displayed before the prompt. If you use a command line option character (that is, "/") as part of the text before the prompt, you must enclose the text in quotes. If no text is specified, choice will only display the prompt.
For example:
-------------------------------------------------- --------------------------------------------------
@echo off
choice / C dme / m "defrag, mem, end"
if errorlevel 3 goto end // The error code with the highest value should be judged first
if errorlevel 2 goto mem
if errotlevel 1 goto defrag
: defrag
c: \ dos \ defrag
goto den
: end
echo good bye
-------------------------------------------------- --------------------------------------------------
After this file runs, it will display:
defrag, men, end [D, M, E]? users can choose dme
Then the if statement will make a judgment, c means that the block labeled end is executed, and the program ends.

for Batch file for command

for command is used to run the specified command on each file in a set of files
grammar:
for [% Variable | %% Variable] in (Set) do Command [CommandLineoptions]
parameter:
[% Variable | %% Variable]
Required parameter, which represents a replaceable parameter. Use% Variable to execute the for command from the command prompt. Use %% Variable to execute the for command in a batch file. Variables are case sensitive and must be represented by an alpha value, such as% A,% B, or% C.
(Set)
Required parameter specifying one or more files, directories, numeric ranges, and text strings to be processed with the specified command. Requires parentheses.
Command
A required parameter specifying the command to be executed for each file, directory, value range, and text string included in the specified (Set).
CommandLineOptions
Specifies any command-line options to be used with the specified command.
As long as the loop command meets the conditions, it will execute the same command multiple times. At the same time, the for loop can be applied to the loop.
For example:
for %% c in (* .bat * .txt)
do type %% c
Meaning: If a file ends with .bat or .txt, the content of the file is displayed.

IN OTHER LANGUAGES

Was this article helpful? Thanks for the feedback Thanks for the feedback

How can we help? How can we help?