SoFunction
Updated on 2025-04-08

BAT Batch File Syntax Page 1/2

A file with the extension bat (can also be cmd under nt/2000/xp/2003) is a batch file.
.bat is a batch file under dos
.cmd is another batch file in the nt kernel command line environment.
From a broader perspective, unix shell scripts and text interpreted and executed by shells in other operating systems and even applications have very similar functions as batch files, and are also interpreted and executed by a dedicated interpreter in behavioral units. This text form is more common name for scripting language. So from a certain extent, scripting languages ​​such as batch, unix shell, awk, basic, and perl are the same, except that the scope of application and the platform of interpretation are different. Some applications even use the term batch processing, and their content and extension are completely different from dos batch processing.
First of all, a batch file is a text file. Each line of this file is a DOS command (mostly it is like the command line we execute at a DOS prompt). You can use Edit under DOS or any text file editing tool such as Windows Notepad.
Non-dos commands can be used in batch files, and even ordinary data files without executable characteristics can be used. This is due to the involvement of the new interpretation platform of Windows system, which makes batch processing applications increasingly "marginalized". Therefore, the batch processing we are discussing should be limited to the dos environment or the command line environment, otherwise many concepts and settings will require relatively large changes.
Secondly, a batch file is a simple program that can control the process of command execution through conditional statements (if) and process control statements (goto). In batch processing, a loop statement (for) can also be used to loop through a command. Of course, the programming ability of batch files is very limited and irregular compared to programming statements such as C language. A batch processing program statement is a series of DOS commands (including internal and external commands), and the ability of batch processing mainly depends on the commands you use.
==== Note ============================
A batch file can also be called a batch program, which is different from a compiled language. As for the C language, a file with an extension of c or cpp can be called a C language file or a C language source code, but only the compiled and connected exe file can be called a C language program. Because the batch file itself is both readable and executable, the boundaries of these titles are relatively vague.
=========================== 
Third, each written batch file is equivalent to an external DOS command. You can put the directory it is in into your DOS search path (path) so that it can run anywhere. A good habit is to create a bat or batch directory on the hard disk (for example, C:\BATCH), and then put all the batch files you wrote into that directory. This way, as long as you set c:\batch in the path, you can run all the batch programs you wrote anywhere.
==== Note =====
In purely in the Dos system, executable programs can be roughly divided into five categories. According to the execution priority, they are: DOSKEY macro command (pre-resident memory), internal commands in them (accommute to memory at any time according to the memory environment), executable programs with com as the extension (loaded directly into memory), executable programs with exe bit extension (loaded into memory after relocation), and batch programs with bat bit extension (analyzed by  , and called the 2nd, 3, 4, and 5 executable programs in order of priority according to their content, analyze one line, execute one line, and the file itself does not load into memory)
============ 
Fourth, under DOS and Win9x/Me systems, the batch file in the root directory of C: disk automatically runs the batch file. The file will be automatically run every time the system starts up. You can put commands that the system needs to run every time it starts up into the file, such as setting the search path, calling in the mouse driver and disk cache, setting system environment variables, etc. Here is an example running under Windows 98:
@ECHO OFF 
PATH C:\WINDOWS;C:\WINDOWS\COMMAND;C:\UCDOS;C:\DOSTools;

C:\SYSTOOLS;C:\WINTOOLS;C:\BATCH 
LH  /X 
LH  /insert 
LH  
SET TEMP=D:\TEMP 
SET TMP=D:\TEMP 
==== Note =====
It is an automatic batch file running in the DOS system, and is interpreted and executed at startup;
In Win9x environment, not only are there many other automatically running batch files, but many variants such as .DOS.W40.BAK.OLD.PWS are also added to adapt to complex environments and changing needs.
==== willsort Editor’s Notes==================
There is a lot to think about in the following categories of commands. The @ in common commands is not a command, and the commonly used commands such as dir and copy are not included. All commands in special commands are commonly used commands for me. It is recommended to divide the commands referenced in batches into three categories: internal commands, external commands, and third-party programs. Another type of internal and external commands is that commands that are specifically used or commonly used in batch processing can be called "batch commands".
The following excerpts about "batch commands" in the MS-DOS 6.22 help document. Of course, some of the concepts and definitions are already a little behind.
Batch commands
A batch file or batch program is a body file containing several MS-DOS commands with the extension .BAT. When the name of the batch program is entered at the command prompt, MS-DOS groups execute commands in this batch program.
Any command that is available at the command prompt is available in the batch program. In addition, the following MS-DOS command is specially used in batch programs.
========== 
Commonly used commands
echo, @, call, pause, rem (small tips: use :: instead of rem) are the most commonly used commands for batch files, so we start with them.
==== Note ===============
First of all, @ is not a command, but a special token for DOS batch processing, which is only used to block command line echoes. Here are some special tokens that may be seen in DOS command line or batch processing:
CR(0D) Command line ending character
Escape(1B) ANSI escape character bootstrap
Space(20) Commonly used parameter delimiter
Tab(09); = Uncommonly used parameter delimiter
+ COPY command file connector
* ? File wildcard
"" String Delimiter
| Command pipe symbol
< > >> File redirector
@ Command line echo mask
/ Parameter switch guide
: Batch Tag Boot
%Batch variable bootstrap
Secondly, :: It can indeed play the role of rem annotation, and it is more concise and effective; but there are two points that need to be paid attention to:
First, except for  :: , any character line starting with  : is regarded as a label in batch processing, and all subsequent contents are directly ignored. It is only for the purpose of distinguishing it from normal labels. It is recommended to use a label that cannot be recognized by goto, that is, a special symbol followed by a non-alphanumeric number.
Second, unlike rem, the character line after :: will not echo when executed, regardless of whether the command line is opened with echo on or not, because the command interpreter does not consider it to be a valid command line. From this point of view, rem will be more applicable than :: in some cases; in addition, rem can be used in files.
===================== 
echo means the character after displaying this command
echo off means that all commands run after this statement do not display the command line itself.
@ is similar to echo off, but it is added at the front of each command line, indicating that the command line that does not display this line at runtime (it can only affect the current line).
call call another batch file (if you call another batch file directly without calling, then after executing that batch file, you will not be able to return the current file and execute subsequent commands for the current file).
pause Running this sentence will pause the execution of the batch and display the prompt for Press any key to continue... on the screen, and wait for the user to press any key to continue.
rem means that the characters after this command are interpreted lines (comments) and are not executed, but are only for reference in the future (equivalent to comments in the program).
==== Note =====
The description here is more confusing, so it is better to use the command line directly to refer to the command line to help it more organized.
------------------------- 
ECHO 
When the program is running, the body in the batch program is displayed or hidden. Can also be used to allow or disable echo of commands.
When running a batch program, MS-DOS generally displays (echos) commands in the batch program on the screen.
Use the ECHO command to turn off this feature.
grammar
ECHO [ON|OFF] 
To display a command using the echo command, the following syntax can be used:
echo [message] 
parameter
ON|OFF 
Specifies whether to allow echo of the command. To display the current ECHO settings, use ECHO without parameters
Order.
message 
Specifies the body text that allows MS-DOS to display on the screen.
------------------- 
CALL 
Call another batch program from one batch program without causing an abort of the first batch.
grammar
CALL [drive:][path]filename [batch-parameters] 
parameter
[drive:][path]filename 
Specifies the name of the batch program to be called and its storage location. The file name must be used as the extension.BAT.
batch-parameters 
Specifies the command line information required by the batch program.
------------------------------- 
PAUSE 
Pauses the execution of the batch program and displays a message, prompting the user to press any key to continue execution. Only in batches
Use this command in the program.
grammar
PAUSE 
REM 
Add comments to the batch file or REM commands can also be used to block commands (in
You can also use semicolons; instead of REM commands, but they cannot be replaced in batch files).
grammar
REM [string] 
parameter
string 
Specifies the command to block or the annotation to include.
======================= 
Example 1: Use edit to edit the file, enter the following content and save it as c:\. After executing the batch file, you can implement it: write all files in the root directory into , start UCDOS, enter WPS and other functions.
The content of the batch file is: Command comment:
@echo off The subsequent command line and current command line are not displayed.
dir c:\*.* >Write the c disk file list to
call c:\ucdos\Calling ucdos
echo Hello Show "Hello"
pause  Pause, wait for the button to continue
rem Prepare to run wps      Comment: Prepare to run wps
cd ucdos  Enter the ucdos directory
wps  Run wps
Parameters of batch file
Batch files can also use parameters like C functions (equivalent to command line parameters of DOS commands), which requires the use of a parameter identifier "%".
%[1-9] represents a parameter. Parameters refer to a string separated by spaces (or Tabs) after the file name when running a batch file. Variables can range from %0 to %9, %0 represents the batch command itself, and other parameter strings are represented in the order of %1 to %9.
Example 2: C: There is a batch of processing files in the root directory with the following contents:
@echo off 
format %1 
If C:\>f a:
Then when executing, %1 means a:, so format %1 is equivalent to format a:, so when the above command is run, format a:
Example 3: C: The name of the batch of processing files in the root directory is, and the content is:
@echo off 
type %1 
type %2 
Then run C:\>t
%1 : Denotes
%2 : Denotes
The above command will then display the contents of the file sequentially.
==== Note ======================
Parameters are also processed as variables in batch processing, so the percentage sign is also used as a bootstrap, followed by a number from 0-9 to form the parameter reference character. The relationship between the reference character and the parameter (for example, %1 and a:  in the above) is similar to the relationship between the variable pointer and the variable value. When we want to reference the eleventh or more parameters, we must move the parameter start pointer of the DOS. The shift command is acting as the role of this moving pointer, which moves the parameter start pointer to the next parameter, similar to the pointer operation in C language. The illustration is as follows:
Initial state, cmd is the command name, which can be referenced with %0
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ 

%0 %1 %2 %3 %4 %5 %6 %7 %8 %9 
After 1 shift, cmd will not be cited
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ 

%0 %1 %2 %3 %4 %5 %6 %7 %8 %9 
After 2 shifts, arg1 is also abandoned, %9 points to empty, and there is no reference meaning.
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 
^ ^ ^ ^ ^ ^ ^ ^ ^ 

%0 %1 %2 %3 %4 %5 %6 %7 %8 
Unfortunately, shift’s inverse operation is not supported in win9x and DOS. Shift only supports the /n parameter in the nt kernel command line environment, and the first parameter can be used as the reference to move the start pointer.
================= 
Special command
if goto choice for is a more advanced command in batch files. If you use these very skillfully, you are an expert in batch files.
1. If is a conditional statement used to determine whether the specified conditions are met and thus decide to execute different commands. There are three formats:
1. If [not] "parameter" == "string" command to be executed
If the parameter is equal to the string specified by (not means unequal, the same below), the condition is true, run the command, otherwise run the next sentence.
Example: if "%1"=="a" format a:
==== 
The description of this point in the command line help of if  is:
IF [NOT] string1==string2 command 
Here are the following points to be noted:
1. Double quotes containing strings are not necessary for syntax, but are just a "air defense" character used in habit.
2. string1 may not be a parameter, it can also be an environment variable, loop variable and other string constants or variables
3. command is not necessary for syntax. String2  followed by a space can form a valid command line.
============================= 
2. if [not] exist [path\] File name Command to be executed
If there is a specified file, the conditions are true, run the command, otherwise run the next sentence.
For example: if exist c:\ type c:\
Indicates that if a c:\ file exists, its contents will be displayed.
****** Note ********
The following usages can also be used:
if exist command 
device refers to the device loaded in the DOS system. Under win98, there are usually:
AUX, PRN, CON, NUL 
COM1, COM2, COM3, COM4 
LPT1, LPT2, LPT3, LPT4 
XMSXXXX0, EMMXXXX0 
A: B: C: ..., 
CLOCK$, CONFIG$, DblBuff$, IFS$HLP$ 
The specific content will vary slightly depending on the hardware and software environment. When using these device names, the following three points need to be ensured:
1. The device does exist (except for devices that are virtualized by the software)
2. The device driver has been loaded (standard devices such as aux, prn are defined by the system by default)
3. The device is ready (mainly refers to a: b: ..., com1..., lpt1..., etc.)
You can check the devices loaded in your system by command mem/d/find/"/i/
In addition, in the DOS system, a device is also considered a special file, and a file can also be called a character device; because both device and file are managed using handles, the handle is the name, similar to a file name, but the handle is not applied to disk management, but to memory management. The so-called device loading refers to allocating a referenceable handle to it in memory.
================================== 
3. If Errorlevel <number> Command to be executed
Many DOS programs will return a numeric value after the run is completed to represent the result (or status) of the program. The if errorlevel command can determine the return value of the program, and determine the execution of different commands based on different return values ​​(the return value must be arranged in order from large to small). If the return value is equal to the specified number, the condition is true and the command is run, otherwise the next sentence will be run.
Such as if Errorlevel 2 goto x2
==== Note ===============
The order of return values ​​from large to small is not necessary, but it is just an idiom when executing commands as goto. When using set as the command, it is usually arranged from small to large. For example, if you need to place the return code into an environment variable, you need to use the following order form:
if errorlevel 1 set el=1 
if errorlevel 2 set el=2 
if errorlevel 3 set el=3 
if errorlevel 4 set el=4 
if errorlevel 5 set el=5 
... 
Of course, the following loop can also be used instead, and the principle is consistent:
for %%e in (1 2 3 4 5 6 7 8...) do if errorlevel %%e set el=%%e 
For more efficient and concise usage, you can refer to another article I wrote about obtaining errorlevel
The reason for this phenomenon is that the judgment condition for comparing return codes if errorlevel is not equal to, but greater than or equal to. Due to the jump characteristic of goto, sorting from small to large will cause jump out at the smaller return code; and due to the "repeat" assignment characteristic of the set command, sorting from large to small will cause the smaller return code to "overwrite" the larger return code.
In addition, although if Errorlevel=<number> command is also a valid command line, it is just to ignore the = as a command line split when interpreting the command line.
=========================== 
2. Goto The batch file runs here and will jump to the label specified by goto (the label is label, followed by a standard string). The goto statement is generally used in conjunction with if, and different command groups are executed according to different conditions.
like:
goto end 
:end 
echo this is the end 
The label is defined by ": string", and the line where the label is located is not executed.
==== willsort Editor's Note
label  is often translated as “label”, but this is not broadly conventional.
goto and: Use it in conjunction to realize jumps in the middle of execution, and then combine it with if, to realize conditional branches of the execution process. Multiple if, can realize grouping of commands, similar to the switch case structure in C or the select case structure in Basic. Large-scale and structured command grouping can realize function functions in high-level languages. The following is a comparison between batch processing and C/Basic in syntax structure:
Batch C / Basic 
goto&: goto&: 
goto&:&if if{}&else{} / if&elseif&endif 
goto&:&if... switch&case / select case 
goto&:&if&set&envar... function() / function(),sub() 
================================== 
3. choice Use this command to allow the user to enter a character (for selection), so as to return different errorlevels according to the user’s choice, and then cooperate with if Errorlevel to run different commands according to the user’s choice.
Note: The choice command is an external command provided by DOS or Windows system. The syntax of choice commands in different versions will be slightly different. Please use choice /? to view the usage.
The command syntax of choice (this syntax is the syntax of the choice command in Windows 2003, and the command syntax of other versions of choice is similar to this):
CHOICE [/C choices] [/N] [/CS] [/T timeout /D choice] [/M text] 
describe:
This tool allows the user to select an item from the selection list and return the index of the selected item.
Parameter list:
/C choices Specify the list of options to create. The default list is "YN".
/N Hide the list of options in the prompt. The prompt is displayed,
The option is still enabled.
/CS Allows to select case-based options. By default, this tool
It is case-free.
/T timeout The number of seconds to pause before making the default selection. The acceptable value is from 0
to 9999. If 0 is specified, there will be no pause, the default option
Will get a choice.
/D choice Specify the default option after nnnn seconds. Characters must be selected using /C
The item specifies a set of selections; at the same time, nnnn must be specified with /T.
/M text Specifies the message to be displayed before prompting. If not specified, the tool only
Show prompt.
/? Show help message.
Notice:
ERRORLEVEL Environment variable is set to the key index selected from the selection set. The first choice listed
Select to return 1, the second option returns 2, etc. If the key pressed by the user is not a valid choice,
This tool will emit a warning sound. If the tool detects an error status, it returns                                                          �
ERRORLEVEL value. If the user presses Ctrl+Break or Ctrl+C, the tool will return 0
ERRORLEVEL value. When using the ERRORLEVEL parameter in a batch program, reduce the parameter
Order.
Example:
CHOICE /? 
CHOICE /C YNC /M "Please press  Y if it is not, or press  C if it is cancelled."
CHOICE /T 10 /C ync /CS /D y 
CHOICE /C ab /M "Option 1 Please select a, option 2 Please select b.”
CHOICE /C ab /N /M "Option 1 Please select a, option 2 Please select b.”
==== willsort Commentary Notes===========================================
I have listed the usage help of choice under win98, and it has been divided
Waits for the user to choose one of a set of choices. 
Wait for the user to select one of the sets of characters to be selected
CHOICE [/C[:]choices] [/N] [/S] [/T[:]c,nn] [text] 
/C[:]choices Specifies allowable keys. Default is YN 
Specify allowed keys (characters to be selected), default is YN
/N Do not display choices and ? at end of prompt string. 
Question marks and characters to be selected in the prompt string are not displayed
/S Treat choice keys as case sensitive. 
Case sensitivity when processing characters to be selected
/T[:]c,nn Default choice to c after nn seconds 
After nn seconds, select c  by default
text Prompt string to display 
Prompt string to display
ERRORLEVEL is set to offset of key user presses in choices. 
ERRORLEVEL is set as the offset value of the character typed by the user in the characters to be selected
If I run the command: CHOICE /C YNC /M "Please press  Y, no, or cancel, press  C."
The screen will display:
Please press Y to confirm, if, press N, or cancel, press C. [Y,N,C]?
Example: The content is as follows (note that when using if errorlevel to determine the return value, the return value should be arranged from high to low):
@echo off 
choice /C dme /M "defrag,mem,end" 
if errorlevel 3 goto end 
if errorlevel 2 goto mem 
if errorlevel 1 goto defrag 
:defrag 
c:\dos\defrag 
goto end 
:mem 
mem 
goto end 
:end 
echo good bye 
After this batch is run, "defrag,mem,end[D,M,E]?" will be displayed. The user can select d m e , and then the if statement makes a judgment based on the user's choice. d represents the execution block with the label defrag, m represents the execution block with the label mem, and e represents the execution block with the label end. In the end, each program block will jump the program to the end label with goto end, and the program will display good bye, and the batch run ends.
12Next pageRead the full text