### Detailed Explanation of Batch Processing under DOS
A `.bat` is a batch processing file under DOS. A `.cmd` is another type of batch processing file in the NT kernel command line environment. From a broader perspective, Unix shell scripts and texts in other operating systems or even applications that are interpreted and executed by the shell have very similar functions to batch processing files. Moreover, they are all interpreted and executed line by line by a dedicated interpreter. A more general term for this text form is scripting language. So, from a certain perspective, scripting languages such as batch, Unix shell, awk, basic, perl, etc., are the same, except that they are applied in different ranges and interpreted on different platforms. Even some applications still use the term "batch processing," but their content and extensions are completely different from those of DOS batch processing.
===================================
First, a batch processing file is a text file. Each line of this file is a DOS command (most of the time, it is just like the command line we execute under the DOS prompt). You can use text file editing tools such as Edit under DOS or Notepad under Windows to create and modify batch processing files.
==== Note ===================
A batch processing file can completely use non-DOS commands, and even ordinary data files that do not have executable characteristics. This is due to the involvement of the new interpretation platform of the Windows system, which makes the application of batch processing more "marginalized". Therefore, the batch processing we discuss should be limited to the DOS environment or command line environment, otherwise, many concepts and settings need to be changed significantly.
========================
Second, a batch processing file is a simple program. You can use conditional statements (if) and process control statements (goto) to control the flow of command execution. In batch processing, you can also use loop statements (for) to execute a command in a loop. Of course, the programming ability of batch processing files is very limited and not standardized compared with programming statements such as the C language. The program statements of batch processing are just one by one DOS commands (including internal commands and external commands), and the ability of batch processing mainly depends on the commands you use.
==== Note ==================
A batch processing file (batch file) can also be called a batch processing program (batch program). This is different from compiled languages. For example, for the C language, files with extensions c or cpp can be called C language files or C language source codes, but only the exe file after compilation and linking can be called a C language program. Because the batch processing file itself has both readability of text and executability of a program, the boundaries of these designations are relatively blurred.
===========================
Third, each well-written batch processing file is equivalent to an external command of DOS. You can put the directory where it is located into your DOS search path (path) so that it can run in any position. A good habit is to create a bat or batch directory (for example, C:\BATCH) on the hard disk, and then put all the batch processing files you write into this directory. In this way, as long as you set c:\batch in the path, you can run all the batch processing programs you write in any position.
==== Note =====
Purely in terms of the DOS system, executable programs can be roughly divided into five categories, arranged in descending order of execution priority: DOSKEY macro commands (pre-resident in memory), internal commands in COMMAND.COM (reside in memory according to the memory environment at any time), executable programs with the com extension (directly loaded into memory by command.com), executable programs with the exe extension (relocated and loaded into memory by command.com), and batch processing programs with the bat extension (interpreted and analyzed by command.com, and call the 2nd, 3rd, 4th, and 5th types of executable programs in order of priority according to its content, analyze one line and execute one line, and the file itself is not loaded into memory)
============
Fourth, under the DOS and Win9x/Me systems, the AUTOEXEC.BAT batch processing file in the root directory of the C drive is an automatically running batch processing file. It will automatically run this file every time the system starts. You can put the commands that need to be run every time the system starts into this file, such as setting the search path, loading the mouse driver and disk cache, setting the system environment variables, etc. The following is an example of an autoexec.bat running under Windows 98:
@ECHO OFF
PATH C:\WINDOWS;C:\WINDOWS\COMMAND;C:\UCDOS;C:\DOSTools;
C:\SYSTOOLS;C:\WINTOOLS;C:\BATCH
LH SMARTDRV.EXE /X
LH DOSKEY.COM /insert
LH CTMOUSE.EXE
SET TEMP=D:\TEMP
SET TMP=D:\TEMP
==== Note =====
AUTOEXEC.BAT is an automatically running batch processing file of the DOS system, which is interpreted and executed when COMMAND.COM starts;
In the Win9x environment, not only many other automatically running batch processing files such as DOSSTART.BAT, WINSTART.BAT, etc., are added to support, but also many variants such as .DOS .W40 .BAK .OLD .PWS, etc., are added to AUTOEXEC.BAT to adapt to complex environments and changing needs.
==== willsort Annotation =============
There are many places worthy of discussion in the following classification of commands. The @ in common commands is not a command, and commands such as dir, copy, etc., which are also very common, are not listed, while all commands in special commands are common commands to me. It is recommended to divide the commands referred to by batch processing into three categories: internal commands, external commands, and third-party programs. And among internal commands and external commands, there is another category of commands that are specially used or often used in batch processing, which can be called "batch processing commands".
The following is an excerpt from the MS-DOS 6.22 help document about "batch processing commands". Of course, some of these concepts and definitions are a bit outdated.
Batch Processing Commands
A batch processing file or batch processing program is a text file containing several MS-DOS commands with the extension .BAT. When the name of the batch processing program is typed at the command prompt, MS-DOS executes the commands in this batch processing program in groups.
Any command that can be used at the command prompt can be used in a batch processing program. In addition, the following MS-DOS commands are specially used in batch processing programs.
==========
Common Commands
echo, @, call, pause, rem (tips: use :: instead of rem) are the most commonly used commands in batch processing files. Let's start learning from them.
==== Note ===========
First, @ is not a command, but a special mark in DOS batch processing, only used to shield command line echoing. The following are some special marks that may be seen in DOS command lines or batch processing:
CR(0D) Command line end character
Escape(1B) ANSI escape character guide character
Space(20) Common parameter delimiter
Tab(09) ; = Less commonly used parameter delimiter
+ COPY command file concatenation character
* ? File wildcards
"" String delimiter
| Command pipeline character
< > >> File redirection character
@ Command line echoing shielding character
/ Parameter switch guide character
: Batch processing label guide character
% Batch processing variable guide character
Second, :: can indeed play the role of rem comment, and it is more concise and effective; but there are two points to note:
First, except for ::, any character line starting with : is regarded as a label in batch processing, and all content after it is directly ignored. Just to distinguish it from normal labels, it is recommended to use a special symbol that cannot be recognized by goto, that is, a special symbol other than letters and numbers is followed after :.
Second, different from rem, the character line after :: will not be echoed during execution, regardless of whether the command line echoing state is turned on by echo on, because the command interpreter does not consider it a valid command line. In this regard, rem will be more applicable than :: in some occasions; in addition, rem can be used in the config.sys file.
=====================
echo means to display the characters after this command.
echo off means that all commands running after this statement do not display the command line itself.
@ is similar to echo off, but it is added in front of each command line, indicating that this line of command is not displayed during running (only affects the current line).
call calls another batch processing file (if you directly call another batch processing file without call, then after executing that batch processing file, you will not be able to return to the current file and execute the subsequent commands of the current file).
pause running this sentence will pause the execution of the batch processing and display the prompt Press any key to continue... on the screen, waiting for the user to press any key to continue.
rem means that the characters after this command are explanatory lines (comments), which are not executed, just for reference for the future (equivalent to comments in the program).
==== Note =====
The description here is relatively chaotic,不如 directly refer to the command line help of each command for a more organized description.
-------------------------
ECHO
When the program runs, it displays or hides the text in the batch processing program. It can also be used to allow or prohibit the echoing of commands.
When running a batch processing program, MS-DOS generally displays (echoes) the commands in the batch processing program on the screen.
Use the ECHO command to turn off this function.
Syntax
ECHO
If you want to use the echo command to display a command, you can use the following syntax:
echo
Parameters
ON|OFF
Specify whether to allow the echoing of commands. If you want to display the current ECHO setting, you can use the ECHO command without parameters.
message
Specify the text that MS-DOS displays on the screen.
-------------------
CALL
Call another batch processing program from a batch processing program without causing the first batch processing to stop.
Syntax
CALL filename
Parameters
filename
Specify the name and storage location of the batch processing program to be called. The file name must use .BAT as the extension.
batch-parameters
Specify the command line information required by the batch processing program.
-------------------------------
PAUSE
Pause the execution of the batch processing program and display a message, prompting the user to press any key to continue execution. This command can only be used in batch processing programs.
Syntax
PAUSE
REM
Add comments in the batch processing file or CONFIG.SYS. The REM command can also be used to shield commands (semicolons ; can be used instead of REM commands in CONFIG.SYS, but not in batch processing files).
Syntax
REM
Parameters
string
Specify the command to be shielded or the comment to be included.
=======================
Example 1: Use edit to edit the a.bat file, enter the following content and save it as c:\a.bat. After executing this batch processing file, the functions of writing all files in the root directory into a.txt, starting UCDOS, entering WPS, etc., can be realized.
The content of the batch processing file: command comments:
@echo off Do not display subsequent command lines and current command line.
dir c:\*.* >a.txt Write the file list of the C drive into a.txt.
call c:\ucdos\ucdos.bat Call ucdos.
echo Hello Display "Hello".
pause Pause and wait for the key to continue.
rem Prepare to run wps Comment: Prepare to run wps.
cd ucdos Enter the ucdos directory.
wps Run wps.
Parameters of Batch Processing Files
Batch processing files can also use parameters like functions in the C language (equivalent to command line parameters of DOS commands). This requires using a parameter identifier "%".
% means parameters. Parameters refer to the strings separated by spaces (or Tab) after the file name when running the batch processing file. Variables can range from %0 to %9. %0 represents the batch processing command itself, and other parameter strings are represented in sequence by %1 to %9.
Example 2: There is a batch processing file named f.bat in the root directory of C, and the content is:
@echo off
format %1
If you execute C:\>f a:
Then when executing f.bat, %1 means a:, so format %1 is equivalent to format a:, so the above command actually executes format a: when running.
Example 3: There is a batch processing file named t.bat in the root directory of C, and the content is:
@echo off
type %1
type %2
Then run C:\>t a.txt b.txt.
%1: Represents a.txt.
%2: Represents b.txt.
Then the above command will sequentially display the contents of the a.txt and b.txt files.
==== Note ===============
Parameters are also treated as variables in batch processing, so the percent sign is also used as a guide character. A number from 0-9 is followed by it to form a parameter reference character. The relationship between the reference character and the parameter (such as %1 and a: in the above text) is similar to the relationship between a variable pointer and a variable value. When we want to reference the eleventh or more parameters, we must move the parameter start pointer of DOS. The shift command acts as this pointer moving role, which moves the parameter start pointer to the next parameter, similar to the pointer operation in the C language. The diagram is as follows:
Initial state, cmd is the command name, which can be referenced by %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 cannot be referenced.
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 discarded, and %9 points to empty, which has no reference meaning.
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | |
%0 %1 %2 %3 %4 %5 %6 %7 %8
Unfortunately, win9x and DOS do not support the reverse operation of shift. Only in the NT kernel command line environment does shift support the /n parameter, which can repeatedly move the start pointer with the first parameter as the benchmark.
=================
Special Commands
if, goto, choice, for are relatively advanced commands in batch processing files. If you use these well, you are an expert in batch processing files.
1. if is a conditional statement used to judge whether the specified conditions are met, so as to decide to execute different commands. There are three formats:
1. if "parameter" == "string" command to be executed.
If the parameter is equal to (not means not equal, the same below) the specified string, then the condition is established, and the command is run; otherwise, the next sentence is run.
Example: if "%1"=="a" format a:
====
The description in the command line help of if about this point is:
IF string1==string2 command.
The following points need to be noted here:
1. The double quotes containing the string are not necessary for grammar, but are just a kind of "anti-air" character used by habit.
2. string1 is not necessarily a parameter, it can also be an environment variable, a loop variable, and other string constants or variables.
3. command is not necessary for grammar, and a space can be followed after string2 to form a valid command line.
=============================
2. if exist file name command to be executed.
If the specified file exists, the condition is established, and the command is run; otherwise, the next sentence is run.
For example: if exist c:\config.sys type c:\config.sys.
It means that if the c:\config.sys file exists, then display its content.
****** Note ********
The following usage can also be used:
if exist command.
device refers to the devices loaded in the DOS system. In 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 be slightly different due to the different hardware and software environments. When using these device names, the following three points need to be ensured:
1. The device does exist (except for the devices virtualized by 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 referring to a: b: ..., com1..., lpt1... etc.).
You can use the command mem/d | find "device" /i to check the devices loaded in your system.
In addition, in the DOS system, the device is also considered a special file, and the file can also be called a character device; because the device (device) and the file are both managed by handles (handle), the handle is the name, similar to the file name, except that the handle is not applied to disk management, but to memory management. The so-called device loading also means that a referenceable handle is allocated for it in memory.
==================================
3. if errorlevel <number> command to be executed.
Many DOS programs return a numerical value to indicate the running result (or status) of the program after running. Through the if errorlevel command, you can judge the return value of the program, and decide to execute different commands according to different return values (the return values must be arranged in descending order). If the return value is equal to the specified number, the condition is established, and the command is run; otherwise, the next sentence is run.
For example, if errorlevel 2 goto x2.
==== Note ===========
The arrangement of return values in descending order is not necessary, but it is just a habitual usage when the command is goto. When using set as the execution command, it is usually arranged in ascending order. For example, if you need to put 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 to replace, the principle is the same:
for %%e in (1 2 3 4 5 6 7 8...) do if errorlevel %%e set el=%%e.
A more efficient and concise usage can refer to another article I wrote about obtaining errorlevel.
The reason for this phenomenon is that the judgment condition of if errorlevel <number> command is not equal, but greater than or equal. Due to the jump characteristic of goto, sorting from small to large will cause jumping out at a smaller return code; and due to the "repeated" assignment characteristic of the set command, sorting from large to small will cause a smaller return code to "override" a larger return code.
In addition, although if errorlevel=<number> command is also a valid command line, it is just that command.com ignores the = as a command line delimiter when interpreting the command line.
===========================
2. goto The batch processing will jump to the label (label is label, the label is defined by : followed by a standard string) specified by goto when running to here. The goto statement is generally used in conjunction with if to execute different command groups according to different conditions.
For example:
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 Annotation
label is often translated as "label", but this is not universally agreed.
goto and : used together can realize the jump in the middle of execution. Combined with if, it can realize the conditional branch of the execution process. Multiple ifs can realize the 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 the function of functions in high-level languages. The following is the comparison of syntax structures between batch processing and C/Basic:
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 Using this command can let the user enter a character (used for selection), so as to return different errorlevels according to the user's selection, and then cooperate with if errorlevel to run different commands according to the user's selection.
Note: The choice command is an external command provided by the DOS or Windows system. The syntax of the choice command 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. The command syntax of choice in other versions is similar to this):
CHOICE
Description:
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 Specifies the option list to be created. The default list is "YN".
/N Hides the option list in the prompt. The message before the prompt is displayed, and the options are still enabled.
/CS Allows selecting case-sensitive options. By default, this tool is case-insensitive.
/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, and the default option will be selected.
/D choice Specifies the default option after nnnn seconds. The character must be in the set of choices specified by /C option; at the same time, /T must be used to specify nnnn.
/M text Specifies the message to be displayed before the prompt. If not specified, the tool only displays the prompt.
/? Displays the help message.
Note:
The ERRORLEVEL environment variable is set to the key index selected from the selection set. The first selected choice returns 1, the second choice returns 2, and so on. If the key pressed by the user is not a valid choice, the tool will make a warning beep. If the tool detects an error state, it will return an ERRORLEVEL value of 255. If the user presses Ctrl+Break or Ctrl+C key, the tool will return an ERRORLEVEL value of 0. When using the ERRORLEVEL parameter in a batch program, arrange the parameters in descending order.
Example:
CHOICE /?
CHOICE /C YNC /M "Please press Y to confirm, N to refuse, or C to cancel."
CHOICE /T 10 /C ync /CS /D y
CHOICE /C ab /M "Please select a for option 1, and b for option 2."
CHOICE /C ab /N /M "Please select a for option 1, and b for option 2."
==== willsort Annotation ===============================
I list the usage help of choice under win98 for reference for distinction.
Waits for the user to choose one of a set of choices.
CHOICE choices] c,nn]
/Cchoices Specifies allowable keys. Default is YN.
/N Do not display choices and ? at end of prompt string.
/S Treat choice keys as case sensitive.
/Tc,nn Default choice to c after nn seconds.
text Prompt string to display.
ERRORLEVEL is set to offset of key user presses in choices.
If I run the command: CHOICE /C YNC /M "Please press Y to confirm, N to refuse, or C to cancel."
The screen will display:
Please press Y to confirm, N to refuse, or C to cancel. ?
Example: The content of test.bat is as follows (note that when using if errorlevel to judge the return value, it should be arranged in descending order of return value):
@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 processing runs, it will display "defrag,mem,end?", the user can choose d, m, e, and then the if statement makes a judgment according to the user's choice. d means executing the program segment labeled defrag, m means executing the program segment labeled mem, e means executing the program segment labeled end. Each program segment finally jumps to the end label with goto end, and then the program will display good bye, and the batch processing ends.
4. for loop command, it will execute the same command multiple times as long as the condition is met.
Syntax:
Execute a specific command for each file in a group of files.
FOR %%variable IN (set) DO command
%%variable specifies a single letter replaceable parameter.
(set) specifies one or a group of files. Wildcards can be used.
command specifies the command to be executed for each file.
command-parameters
Specify parameters or command line switches for a specific command.
For example, there is a line in a batch processing file:
for %%c in (*.bat *.txt) do type %%c.
Then this command line will display the contents of all files with extensions bat and txt in the current directory.
==== willsort Annotation =====================================================
It needs to be pointed out that when the string in () is not a single or multiple file names, it will simply be regarded as a string replacement. This feature, combined with the feature that multiple strings can be embedded in (), it is obvious that for can be regarded as a traversal loop.
Of course, in the command line environment of the nt/2000/xp/2003 series, for is given more features, so that it can analyze the output of commands or strings in files, and there are also many switches used to expand the file replacement function.
========================================================================
Batch Processing Examples
1. IF-EXIST
1) First, use Notepad to create a test1.bat batch processing file in C:\. The file content is as follows:
@echo off
IF EXIST \AUTOEXEC.BAT TYPE \AUTOEXEC.BAT
IF NOT EXIST \AUTOEXEC.BAT ECHO \AUTOEXEC.BAT does not exist.
Then run it:
C:\>TEST1.BAT.
If the AUTOEXEC.BAT file exists in C:\, then its content will be displayed. If it does not exist, the batch processing will prompt you that the file does not exist.
2) Then create a test2.bat file with the following content:
@ECHO OFF
IF EXIST \%1 TYPE \%1
IF NOT EXIST \%1 ECHO \%1 does not exist.
Execute:
C:\>TEST2 AUTOEXEC.BAT.
The running result of this command is the same as above.
Description:
(1) IF EXIST is used to test whether the file exists. The format is:
IF EXIST command.
(2) The %1 in the test2.bat file is a parameter. DOS allows passing 9 batch parameter information to the batch processing file, which are %1~%9 respectively (%0 represents the test2 command itself). This is a bit like the relationship between actual parameters and formal parameters in programming. %1 is a formal parameter, and AUTOEXEC.BAT is an actual parameter.
==== willsort Annotation =====================================================
DOS does not have the limit of "allowing to pass 9 batch parameter information". The number of parameters will only be limited by the command line length and the processing ability of the called command. However, in the batch processing program, at the same time, you can only refer to 10 parameters, because DOS only gives these ten parameter reference characters %0~%9.
========================================================================
3) Further, create a file named TEST3.BAT with the following content:
@echo off
IF "%1" == "A" ECHO XIAO
IF "%2" == "B" ECHO TIAN
IF "%3" == "C" ECHO XIN.
If you run:
C:\>TEST3 A B C.
The screen will display:
XIAO
TIAN
XIN.
If you run:
C:\>TEST3 A B.
The screen will display:
XIAO
TIAN.
During this command execution, DOS will assign an empty string to parameter %3.
2. IF-ERRORLEVEL.
Create TEST4.BAT with the following content:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 1 ECHO File copy failed.
IF ERRORLEVEL 0 ECHO File copied successfully.
Then execute the file:
C:\>TEST4.
If the file copy is successful, the screen will display "File copied successfully", otherwise it will display "File copy failed".
IF ERRORLEVEL is used to test the return value of its previous DOS command. Note that it is only the return value of the previous command, and the return values must be judged in descending order.
Therefore, the following batch processing file is wrong:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 0 ECHO File copied successfully.
IF ERRORLEVEL 1 ECHO File not found.
IF ERRORLEVEL 2 ECHO User aborted copy operation by ctrl-c.
IF ERRORLEVEL 3 ECHO Pre-set error prevented file copy operation.
IF ERRORLEVEL 4 ECHO Write error during copy operation.
No matter whether the copy is successful or not, the following:
File not found.
User aborted copy operation by ctrl-c.
Pre-set error prevented file copy operation.
Write error during copy operation.
All will be displayed.
The following are the return values of several common commands and their meanings:
backup
0 Backup successful.
1 Backup file not found.
2 File sharing conflict prevented backup from completing.
3 User aborted backup by ctrl-c.
4 Backup operation aborted due to a fatal error.
diskcomp
0 Disks compared the same.
1 Disks compared differently.
2 User aborted comparison operation by ctrl-c.
3 Comparison operation aborted due to a fatal error.
4 Pre-set error aborted comparison.
diskcopy
0 Disk copy operation successful.
1 Non-fatal disk read/write error.
2 User ended copy operation by ctrl-c.
3 Disk copy aborted due to a fatal processing error.
4 Pre-set error prevented copy operation.
format
0 Formatting successful.
3 User:)
A `.bat` is a batch processing file under DOS. A `.cmd` is another type of batch processing file in the NT kernel command line environment. From a broader perspective, Unix shell scripts and texts in other operating systems or even applications that are interpreted and executed by the shell have very similar functions to batch processing files. Moreover, they are all interpreted and executed line by line by a dedicated interpreter. A more general term for this text form is scripting language. So, from a certain perspective, scripting languages such as batch, Unix shell, awk, basic, perl, etc., are the same, except that they are applied in different ranges and interpreted on different platforms. Even some applications still use the term "batch processing," but their content and extensions are completely different from those of DOS batch processing.
===================================
First, a batch processing file is a text file. Each line of this file is a DOS command (most of the time, it is just like the command line we execute under the DOS prompt). You can use text file editing tools such as Edit under DOS or Notepad under Windows to create and modify batch processing files.
==== Note ===================
A batch processing file can completely use non-DOS commands, and even ordinary data files that do not have executable characteristics. This is due to the involvement of the new interpretation platform of the Windows system, which makes the application of batch processing more "marginalized". Therefore, the batch processing we discuss should be limited to the DOS environment or command line environment, otherwise, many concepts and settings need to be changed significantly.
========================
Second, a batch processing file is a simple program. You can use conditional statements (if) and process control statements (goto) to control the flow of command execution. In batch processing, you can also use loop statements (for) to execute a command in a loop. Of course, the programming ability of batch processing files is very limited and not standardized compared with programming statements such as the C language. The program statements of batch processing are just one by one DOS commands (including internal commands and external commands), and the ability of batch processing mainly depends on the commands you use.
==== Note ==================
A batch processing file (batch file) can also be called a batch processing program (batch program). This is different from compiled languages. For example, for the C language, files with extensions c or cpp can be called C language files or C language source codes, but only the exe file after compilation and linking can be called a C language program. Because the batch processing file itself has both readability of text and executability of a program, the boundaries of these designations are relatively blurred.
===========================
Third, each well-written batch processing file is equivalent to an external command of DOS. You can put the directory where it is located into your DOS search path (path) so that it can run in any position. A good habit is to create a bat or batch directory (for example, C:\BATCH) on the hard disk, and then put all the batch processing files you write into this directory. In this way, as long as you set c:\batch in the path, you can run all the batch processing programs you write in any position.
==== Note =====
Purely in terms of the DOS system, executable programs can be roughly divided into five categories, arranged in descending order of execution priority: DOSKEY macro commands (pre-resident in memory), internal commands in COMMAND.COM (reside in memory according to the memory environment at any time), executable programs with the com extension (directly loaded into memory by command.com), executable programs with the exe extension (relocated and loaded into memory by command.com), and batch processing programs with the bat extension (interpreted and analyzed by command.com, and call the 2nd, 3rd, 4th, and 5th types of executable programs in order of priority according to its content, analyze one line and execute one line, and the file itself is not loaded into memory)
============
Fourth, under the DOS and Win9x/Me systems, the AUTOEXEC.BAT batch processing file in the root directory of the C drive is an automatically running batch processing file. It will automatically run this file every time the system starts. You can put the commands that need to be run every time the system starts into this file, such as setting the search path, loading the mouse driver and disk cache, setting the system environment variables, etc. The following is an example of an autoexec.bat running under Windows 98:
@ECHO OFF
PATH C:\WINDOWS;C:\WINDOWS\COMMAND;C:\UCDOS;C:\DOSTools;
C:\SYSTOOLS;C:\WINTOOLS;C:\BATCH
LH SMARTDRV.EXE /X
LH DOSKEY.COM /insert
LH CTMOUSE.EXE
SET TEMP=D:\TEMP
SET TMP=D:\TEMP
==== Note =====
AUTOEXEC.BAT is an automatically running batch processing file of the DOS system, which is interpreted and executed when COMMAND.COM starts;
In the Win9x environment, not only many other automatically running batch processing files such as DOSSTART.BAT, WINSTART.BAT, etc., are added to support, but also many variants such as .DOS .W40 .BAK .OLD .PWS, etc., are added to AUTOEXEC.BAT to adapt to complex environments and changing needs.
==== willsort Annotation =============
There are many places worthy of discussion in the following classification of commands. The @ in common commands is not a command, and commands such as dir, copy, etc., which are also very common, are not listed, while all commands in special commands are common commands to me. It is recommended to divide the commands referred to by batch processing into three categories: internal commands, external commands, and third-party programs. And among internal commands and external commands, there is another category of commands that are specially used or often used in batch processing, which can be called "batch processing commands".
The following is an excerpt from the MS-DOS 6.22 help document about "batch processing commands". Of course, some of these concepts and definitions are a bit outdated.
Batch Processing Commands
A batch processing file or batch processing program is a text file containing several MS-DOS commands with the extension .BAT. When the name of the batch processing program is typed at the command prompt, MS-DOS executes the commands in this batch processing program in groups.
Any command that can be used at the command prompt can be used in a batch processing program. In addition, the following MS-DOS commands are specially used in batch processing programs.
==========
Common Commands
echo, @, call, pause, rem (tips: use :: instead of rem) are the most commonly used commands in batch processing files. Let's start learning from them.
==== Note ===========
First, @ is not a command, but a special mark in DOS batch processing, only used to shield command line echoing. The following are some special marks that may be seen in DOS command lines or batch processing:
CR(0D) Command line end character
Escape(1B) ANSI escape character guide character
Space(20) Common parameter delimiter
Tab(09) ; = Less commonly used parameter delimiter
+ COPY command file concatenation character
* ? File wildcards
"" String delimiter
| Command pipeline character
< > >> File redirection character
@ Command line echoing shielding character
/ Parameter switch guide character
: Batch processing label guide character
% Batch processing variable guide character
Second, :: can indeed play the role of rem comment, and it is more concise and effective; but there are two points to note:
First, except for ::, any character line starting with : is regarded as a label in batch processing, and all content after it is directly ignored. Just to distinguish it from normal labels, it is recommended to use a special symbol that cannot be recognized by goto, that is, a special symbol other than letters and numbers is followed after :.
Second, different from rem, the character line after :: will not be echoed during execution, regardless of whether the command line echoing state is turned on by echo on, because the command interpreter does not consider it a valid command line. In this regard, rem will be more applicable than :: in some occasions; in addition, rem can be used in the config.sys file.
=====================
echo means to display the characters after this command.
echo off means that all commands running after this statement do not display the command line itself.
@ is similar to echo off, but it is added in front of each command line, indicating that this line of command is not displayed during running (only affects the current line).
call calls another batch processing file (if you directly call another batch processing file without call, then after executing that batch processing file, you will not be able to return to the current file and execute the subsequent commands of the current file).
pause running this sentence will pause the execution of the batch processing and display the prompt Press any key to continue... on the screen, waiting for the user to press any key to continue.
rem means that the characters after this command are explanatory lines (comments), which are not executed, just for reference for the future (equivalent to comments in the program).
==== Note =====
The description here is relatively chaotic,不如 directly refer to the command line help of each command for a more organized description.
-------------------------
ECHO
When the program runs, it displays or hides the text in the batch processing program. It can also be used to allow or prohibit the echoing of commands.
When running a batch processing program, MS-DOS generally displays (echoes) the commands in the batch processing program on the screen.
Use the ECHO command to turn off this function.
Syntax
ECHO
If you want to use the echo command to display a command, you can use the following syntax:
echo
Parameters
ON|OFF
Specify whether to allow the echoing of commands. If you want to display the current ECHO setting, you can use the ECHO command without parameters.
message
Specify the text that MS-DOS displays on the screen.
-------------------
CALL
Call another batch processing program from a batch processing program without causing the first batch processing to stop.
Syntax
CALL filename
Parameters
filename
Specify the name and storage location of the batch processing program to be called. The file name must use .BAT as the extension.
batch-parameters
Specify the command line information required by the batch processing program.
-------------------------------
PAUSE
Pause the execution of the batch processing program and display a message, prompting the user to press any key to continue execution. This command can only be used in batch processing programs.
Syntax
PAUSE
REM
Add comments in the batch processing file or CONFIG.SYS. The REM command can also be used to shield commands (semicolons ; can be used instead of REM commands in CONFIG.SYS, but not in batch processing files).
Syntax
REM
Parameters
string
Specify the command to be shielded or the comment to be included.
=======================
Example 1: Use edit to edit the a.bat file, enter the following content and save it as c:\a.bat. After executing this batch processing file, the functions of writing all files in the root directory into a.txt, starting UCDOS, entering WPS, etc., can be realized.
The content of the batch processing file: command comments:
@echo off Do not display subsequent command lines and current command line.
dir c:\*.* >a.txt Write the file list of the C drive into a.txt.
call c:\ucdos\ucdos.bat Call ucdos.
echo Hello Display "Hello".
pause Pause and wait for the key to continue.
rem Prepare to run wps Comment: Prepare to run wps.
cd ucdos Enter the ucdos directory.
wps Run wps.
Parameters of Batch Processing Files
Batch processing files can also use parameters like functions in the C language (equivalent to command line parameters of DOS commands). This requires using a parameter identifier "%".
% means parameters. Parameters refer to the strings separated by spaces (or Tab) after the file name when running the batch processing file. Variables can range from %0 to %9. %0 represents the batch processing command itself, and other parameter strings are represented in sequence by %1 to %9.
Example 2: There is a batch processing file named f.bat in the root directory of C, and the content is:
@echo off
format %1
If you execute C:\>f a:
Then when executing f.bat, %1 means a:, so format %1 is equivalent to format a:, so the above command actually executes format a: when running.
Example 3: There is a batch processing file named t.bat in the root directory of C, and the content is:
@echo off
type %1
type %2
Then run C:\>t a.txt b.txt.
%1: Represents a.txt.
%2: Represents b.txt.
Then the above command will sequentially display the contents of the a.txt and b.txt files.
==== Note ===============
Parameters are also treated as variables in batch processing, so the percent sign is also used as a guide character. A number from 0-9 is followed by it to form a parameter reference character. The relationship between the reference character and the parameter (such as %1 and a: in the above text) is similar to the relationship between a variable pointer and a variable value. When we want to reference the eleventh or more parameters, we must move the parameter start pointer of DOS. The shift command acts as this pointer moving role, which moves the parameter start pointer to the next parameter, similar to the pointer operation in the C language. The diagram is as follows:
Initial state, cmd is the command name, which can be referenced by %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 cannot be referenced.
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 discarded, and %9 points to empty, which has no reference meaning.
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | |
%0 %1 %2 %3 %4 %5 %6 %7 %8
Unfortunately, win9x and DOS do not support the reverse operation of shift. Only in the NT kernel command line environment does shift support the /n parameter, which can repeatedly move the start pointer with the first parameter as the benchmark.
=================
Special Commands
if, goto, choice, for are relatively advanced commands in batch processing files. If you use these well, you are an expert in batch processing files.
1. if is a conditional statement used to judge whether the specified conditions are met, so as to decide to execute different commands. There are three formats:
1. if "parameter" == "string" command to be executed.
If the parameter is equal to (not means not equal, the same below) the specified string, then the condition is established, and the command is run; otherwise, the next sentence is run.
Example: if "%1"=="a" format a:
====
The description in the command line help of if about this point is:
IF string1==string2 command.
The following points need to be noted here:
1. The double quotes containing the string are not necessary for grammar, but are just a kind of "anti-air" character used by habit.
2. string1 is not necessarily a parameter, it can also be an environment variable, a loop variable, and other string constants or variables.
3. command is not necessary for grammar, and a space can be followed after string2 to form a valid command line.
=============================
2. if exist file name command to be executed.
If the specified file exists, the condition is established, and the command is run; otherwise, the next sentence is run.
For example: if exist c:\config.sys type c:\config.sys.
It means that if the c:\config.sys file exists, then display its content.
****** Note ********
The following usage can also be used:
if exist command.
device refers to the devices loaded in the DOS system. In 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 be slightly different due to the different hardware and software environments. When using these device names, the following three points need to be ensured:
1. The device does exist (except for the devices virtualized by 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 referring to a: b: ..., com1..., lpt1... etc.).
You can use the command mem/d | find "device" /i to check the devices loaded in your system.
In addition, in the DOS system, the device is also considered a special file, and the file can also be called a character device; because the device (device) and the file are both managed by handles (handle), the handle is the name, similar to the file name, except that the handle is not applied to disk management, but to memory management. The so-called device loading also means that a referenceable handle is allocated for it in memory.
==================================
3. if errorlevel <number> command to be executed.
Many DOS programs return a numerical value to indicate the running result (or status) of the program after running. Through the if errorlevel command, you can judge the return value of the program, and decide to execute different commands according to different return values (the return values must be arranged in descending order). If the return value is equal to the specified number, the condition is established, and the command is run; otherwise, the next sentence is run.
For example, if errorlevel 2 goto x2.
==== Note ===========
The arrangement of return values in descending order is not necessary, but it is just a habitual usage when the command is goto. When using set as the execution command, it is usually arranged in ascending order. For example, if you need to put 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 to replace, the principle is the same:
for %%e in (1 2 3 4 5 6 7 8...) do if errorlevel %%e set el=%%e.
A more efficient and concise usage can refer to another article I wrote about obtaining errorlevel.
The reason for this phenomenon is that the judgment condition of if errorlevel <number> command is not equal, but greater than or equal. Due to the jump characteristic of goto, sorting from small to large will cause jumping out at a smaller return code; and due to the "repeated" assignment characteristic of the set command, sorting from large to small will cause a smaller return code to "override" a larger return code.
In addition, although if errorlevel=<number> command is also a valid command line, it is just that command.com ignores the = as a command line delimiter when interpreting the command line.
===========================
2. goto The batch processing will jump to the label (label is label, the label is defined by : followed by a standard string) specified by goto when running to here. The goto statement is generally used in conjunction with if to execute different command groups according to different conditions.
For example:
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 Annotation
label is often translated as "label", but this is not universally agreed.
goto and : used together can realize the jump in the middle of execution. Combined with if, it can realize the conditional branch of the execution process. Multiple ifs can realize the 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 the function of functions in high-level languages. The following is the comparison of syntax structures between batch processing and C/Basic:
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 Using this command can let the user enter a character (used for selection), so as to return different errorlevels according to the user's selection, and then cooperate with if errorlevel to run different commands according to the user's selection.
Note: The choice command is an external command provided by the DOS or Windows system. The syntax of the choice command 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. The command syntax of choice in other versions is similar to this):
CHOICE
Description:
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 Specifies the option list to be created. The default list is "YN".
/N Hides the option list in the prompt. The message before the prompt is displayed, and the options are still enabled.
/CS Allows selecting case-sensitive options. By default, this tool is case-insensitive.
/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, and the default option will be selected.
/D choice Specifies the default option after nnnn seconds. The character must be in the set of choices specified by /C option; at the same time, /T must be used to specify nnnn.
/M text Specifies the message to be displayed before the prompt. If not specified, the tool only displays the prompt.
/? Displays the help message.
Note:
The ERRORLEVEL environment variable is set to the key index selected from the selection set. The first selected choice returns 1, the second choice returns 2, and so on. If the key pressed by the user is not a valid choice, the tool will make a warning beep. If the tool detects an error state, it will return an ERRORLEVEL value of 255. If the user presses Ctrl+Break or Ctrl+C key, the tool will return an ERRORLEVEL value of 0. When using the ERRORLEVEL parameter in a batch program, arrange the parameters in descending order.
Example:
CHOICE /?
CHOICE /C YNC /M "Please press Y to confirm, N to refuse, or C to cancel."
CHOICE /T 10 /C ync /CS /D y
CHOICE /C ab /M "Please select a for option 1, and b for option 2."
CHOICE /C ab /N /M "Please select a for option 1, and b for option 2."
==== willsort Annotation ===============================
I list the usage help of choice under win98 for reference for distinction.
Waits for the user to choose one of a set of choices.
CHOICE choices] c,nn]
/Cchoices Specifies allowable keys. Default is YN.
/N Do not display choices and ? at end of prompt string.
/S Treat choice keys as case sensitive.
/Tc,nn Default choice to c after nn seconds.
text Prompt string to display.
ERRORLEVEL is set to offset of key user presses in choices.
If I run the command: CHOICE /C YNC /M "Please press Y to confirm, N to refuse, or C to cancel."
The screen will display:
Please press Y to confirm, N to refuse, or C to cancel. ?
Example: The content of test.bat is as follows (note that when using if errorlevel to judge the return value, it should be arranged in descending order of return value):
@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 processing runs, it will display "defrag,mem,end?", the user can choose d, m, e, and then the if statement makes a judgment according to the user's choice. d means executing the program segment labeled defrag, m means executing the program segment labeled mem, e means executing the program segment labeled end. Each program segment finally jumps to the end label with goto end, and then the program will display good bye, and the batch processing ends.
4. for loop command, it will execute the same command multiple times as long as the condition is met.
Syntax:
Execute a specific command for each file in a group of files.
FOR %%variable IN (set) DO command
%%variable specifies a single letter replaceable parameter.
(set) specifies one or a group of files. Wildcards can be used.
command specifies the command to be executed for each file.
command-parameters
Specify parameters or command line switches for a specific command.
For example, there is a line in a batch processing file:
for %%c in (*.bat *.txt) do type %%c.
Then this command line will display the contents of all files with extensions bat and txt in the current directory.
==== willsort Annotation =====================================================
It needs to be pointed out that when the string in () is not a single or multiple file names, it will simply be regarded as a string replacement. This feature, combined with the feature that multiple strings can be embedded in (), it is obvious that for can be regarded as a traversal loop.
Of course, in the command line environment of the nt/2000/xp/2003 series, for is given more features, so that it can analyze the output of commands or strings in files, and there are also many switches used to expand the file replacement function.
========================================================================
Batch Processing Examples
1. IF-EXIST
1) First, use Notepad to create a test1.bat batch processing file in C:\. The file content is as follows:
@echo off
IF EXIST \AUTOEXEC.BAT TYPE \AUTOEXEC.BAT
IF NOT EXIST \AUTOEXEC.BAT ECHO \AUTOEXEC.BAT does not exist.
Then run it:
C:\>TEST1.BAT.
If the AUTOEXEC.BAT file exists in C:\, then its content will be displayed. If it does not exist, the batch processing will prompt you that the file does not exist.
2) Then create a test2.bat file with the following content:
@ECHO OFF
IF EXIST \%1 TYPE \%1
IF NOT EXIST \%1 ECHO \%1 does not exist.
Execute:
C:\>TEST2 AUTOEXEC.BAT.
The running result of this command is the same as above.
Description:
(1) IF EXIST is used to test whether the file exists. The format is:
IF EXIST command.
(2) The %1 in the test2.bat file is a parameter. DOS allows passing 9 batch parameter information to the batch processing file, which are %1~%9 respectively (%0 represents the test2 command itself). This is a bit like the relationship between actual parameters and formal parameters in programming. %1 is a formal parameter, and AUTOEXEC.BAT is an actual parameter.
==== willsort Annotation =====================================================
DOS does not have the limit of "allowing to pass 9 batch parameter information". The number of parameters will only be limited by the command line length and the processing ability of the called command. However, in the batch processing program, at the same time, you can only refer to 10 parameters, because DOS only gives these ten parameter reference characters %0~%9.
========================================================================
3) Further, create a file named TEST3.BAT with the following content:
@echo off
IF "%1" == "A" ECHO XIAO
IF "%2" == "B" ECHO TIAN
IF "%3" == "C" ECHO XIN.
If you run:
C:\>TEST3 A B C.
The screen will display:
XIAO
TIAN
XIN.
If you run:
C:\>TEST3 A B.
The screen will display:
XIAO
TIAN.
During this command execution, DOS will assign an empty string to parameter %3.
2. IF-ERRORLEVEL.
Create TEST4.BAT with the following content:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 1 ECHO File copy failed.
IF ERRORLEVEL 0 ECHO File copied successfully.
Then execute the file:
C:\>TEST4.
If the file copy is successful, the screen will display "File copied successfully", otherwise it will display "File copy failed".
IF ERRORLEVEL is used to test the return value of its previous DOS command. Note that it is only the return value of the previous command, and the return values must be judged in descending order.
Therefore, the following batch processing file is wrong:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 0 ECHO File copied successfully.
IF ERRORLEVEL 1 ECHO File not found.
IF ERRORLEVEL 2 ECHO User aborted copy operation by ctrl-c.
IF ERRORLEVEL 3 ECHO Pre-set error prevented file copy operation.
IF ERRORLEVEL 4 ECHO Write error during copy operation.
No matter whether the copy is successful or not, the following:
File not found.
User aborted copy operation by ctrl-c.
Pre-set error prevented file copy operation.
Write error during copy operation.
All will be displayed.
The following are the return values of several common commands and their meanings:
backup
0 Backup successful.
1 Backup file not found.
2 File sharing conflict prevented backup from completing.
3 User aborted backup by ctrl-c.
4 Backup operation aborted due to a fatal error.
diskcomp
0 Disks compared the same.
1 Disks compared differently.
2 User aborted comparison operation by ctrl-c.
3 Comparison operation aborted due to a fatal error.
4 Pre-set error aborted comparison.
diskcopy
0 Disk copy operation successful.
1 Non-fatal disk read/write error.
2 User ended copy operation by ctrl-c.
3 Disk copy aborted due to a fatal processing error.
4 Pre-set error prevented copy operation.
format
0 Formatting successful.
3 User:)
