BAT file syntax and tricks

BAT file syntax and skills (writing and use of bat files) (reproduced 1)  
 

More useful things More useful things 
First of all, a batch 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 at the DOS prompt), you can Create and modify batch files using any text file editing tool such as Edit under DOS or Notepad for Windows. 
 
Secondly, a batch file is a simple program that can control the flow of command execution through conditional statements (if) and flow control statements (goto). In batch processing, a loop statement (for) can also be used to execute a command in a loop. . Of course, the programming capabilities of batch files are very limited and non-standard compared to programming statements such as C language. Batch program statements are DOS commands (including internal commands and external commands), and the ability of batch processing mainly depends on the commands you use. 
 
Third, every prepared batch file is equivalent to a DOS external command, and you can put its directory into your DOS search path (path) to make it run anywhere. A good habit is to create a bat or batch directory on the hard disk (eg C:\BATCH), and then put all the batch files you write in this directory, so as long as you set c:\batch in the path, you You can run all the batch programs you write anywhere. 
 
Fourth, under DOS and Win9x/Me systems, the AUTOEXEC.BAT batch file in the root directory of the C: disk is an automatic batch file that runs automatically every time the system starts. Put the commands that need to be run at all times into this file, such as setting the search path, transferring the mouse driver and disk cache, setting system environment variables, etc. The following is an example of autoexec.bat running under Windows 98:

?
1
2
3
4
5
6
7
@ 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

 The role of batch processing 
Simply put, the role of batch processing is to automatically execute multiple commands continuously. 
 
Here is the simplest application: when starting the wps software, it must be executed every time (> the previous content represents the DOS prompt): 
C:\>cd wps 
C:\WPS>spdos 
C:\WPS>py 
C: \WPS>wbx 
C:\WPS>wps 
If you do this every time before using WPS, do you think it is very troublesome? 
 
Well, using batch processing, you can simplify these troublesome operations. First, we write a runwps.bat batch file, the content is as follows: 

?
1
2
3
4
5
6
7
8
@ echo off 
c: 
cd \wps 
spdos 
py 
wbx 
wps 
cd \

In the future, every time we enter wps, we only need to run the batch file runwps. 
 
Common commands 
 
echo, @, call, pause, rem (tip: use :: instead of rem) are the most commonly used commands in batch files, and we will start with them. 
echo means to display the character after this command 
echo off means that all running commands after this statement do not display the command line itself 
@ is similar to echo off, but it is added to the front of each command line, which means that it does not display when running The command line for this line (only affects the current line). 
call calls another batch file (if you directly call another batch file without calling, then after executing that batch file, you will not be able to return to the current file and execute subsequent commands of the current file). 
pause Running this sentence will pause the execution of the batch and display the prompt Press any key to continue... on the screen, wait for the user to press any key and continue after 
rem means that the character after this command is an explanation line (comment), not executed, just For your own future reference (equivalent to comments in the program). 
 
Example 1: Edit the a.bat file with edit, and save the file as c:\a.bat after entering the following contents. After executing the batch file, you can realize: write all files in the root directory into a.txt, start UCDOS, and enter WPS and other functions. 
 
  The contents of the batch file are: Command comments: 
 
    @echo off Do not display subsequent command lines and current command lines 
    dir c:\*.* >a.txt Write the list of files on the c drive to a.txt 
    call c:\ucdos\ucdos .bat calls ucdos 
    echo hello display "hello" 
    pause pause, wait for the key to continue 
    rem prepare to run wps Note: prepare to run wps 
    cd ucdos enter the ucdos directory 
    wps run wps   
 
batch file parameters 
 
batch files can also use parameters like C language functions ( Equivalent to command-line arguments of DOS commands), which requires the use of an argument specifier "%". 
 
%[1-9] represents the parameter, the parameter refers to the string separated by spaces (or Tab) added after the file name when running the batch file. Variables can be from %0 to %9, where %0 represents the batch command itself, and other parameter strings are represented in the order of %1 to %9. 
 
Example 2: There is a batch file named f.bat in the root directory of C:, and the content is: 

?
1
2
@ echo off 
format %1

If C:\>fa: 
is executed, then when f.bat is executed, %1 means a:, so format %1 is equivalent to format a:, so the actual execution of the above command is format a: 
 
Example 3: The batch file in the root directory of C: is named t.bat, and the content is: 

?
1
2
3
@ echo off 
type %1 
type %2

Then run C:\>t a.txt b.txt 
%1 : means a.txt 
%2 : means b.txt> 
Then the above command will display the contents of the a.txt and b.txt files sequentially. The special command if goto choice for is a relatively advanced command in batch files. If you are proficient in using these commands, you are an expert in batch files. First, if is a conditional statement, which is used to judge whether the specified conditions are met, and thus decide to execute different commands. There are three formats:  1. if [not] "parameter" == "string"  If the parameter of the command to be executed is equal to the specified string (not means not equal, the same below), the condition is satisfied, run the command, otherwise run the next one sentence. Example: if "%1"=="a" format a:  2. if [not] exist [path\]file name  If the command to be executed has the specified file, the condition is satisfied, run the command, otherwise run the next sentence. Such as: if exist c:\config.sys type c:\config.sys  means that if the c:\config.sys file exists, its content will be displayed. 3. if errorlevel <number> Commands to be executed Many DOS programs will return a numerical value after the operation is completed to indicate the result (or status) of the program. The return value of the program can be judged by the if errorlevel command, and different commands can be executed according to different return values. (The return values ​​must be in descending order). If the return value is equal to the specified number, the condition is true, run the command, otherwise run the next sentence. Such as if errorlevel 2 goto x2 
  
 
 

 

 

 

 

 


 


 

 

 

 
2. When the goto batch file runs here, it will jump to the label specified by goto (the label is the label, and the label is defined by: followed by a standard string). The goto statement is generally used in conjunction with if to execute different tasks according to different conditions. command group. 
 
Such as: 
 
goto end 
 
:end 
echo this is the end The 
 
label is defined with ":string", and the line where the label is located will not be executed. 
 
3. choice Use this command to allow the user to input 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 the DOS or Windows system. Different versions of the choice command have slightly different syntax. 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] 
 
Description: 
  This tool allows the user to select an item from a selection list and returns the index of the selected item. 
 
Parameter list: 
 /C choices Specifies a list of options to create. The default list is "YN". 
 
 /N hides the option list from the prompt. The message preceding the prompt is displayed, and the option is still enabled. 
 
 /CS Allows selection of case-sensitive options. By default, this tool is case-insensitive. 
 
 /T timeout The number of seconds to pause before making a default selection. Acceptable values ​​are 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 choice after nnnn seconds. The character must be in a set of choices specified with the /C option; also, nnnn must be specified with the /T option. 
 
 /M text Specifies a message to display before prompting. If not specified, the tool only displays a hint. 
 
 /? Displays a help message. 
 
 Note: 
 The ERRORLEVEL environment variable is set to the key index selected from the selection set. The first choice listed returns 1, the second choice returns 2, and so on. If the user presses a key that is not a valid selection, the tool emits a warning beep. If the tool detects an error condition, it returns an ERRORLEVEL value of 255. If the user presses Ctrl+Break or Ctrl+C, the tool returns 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 "Press Y to confirm, N if no, or C to cancel." 
 CHOICE /T 10 /C ync /CS /D y 
 CHOICE /C ab /M "Option 1 Please choose a, option 2 please choose b." 
 CHOICE /C ab /N /M "Option 1 please choose a, option 2 please choose b. " 
  
If I run the command: CHOICE /C YNC /M " Press Y to confirm, N if no, or C to cancel. "
The screen will display: 
Press Y to confirm, N if no, or C to cancel. [Y,N,C]? 
  
  
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 the return value): 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@ echo off 
choice /C dme /M "defrag,mem,end" 
if errorlevel 3 goto end 
if errorlevel 2 goto mem 
if errotlevel 1 goto defrag 
   
:defrag 
c:\dos\defrag 
goto end 
   
:mem 
mem 
goto end 
   
:end 
echo good bye

After this batch runs, it will display "defrag,mem,end[D,M,E]?", the user can choose dme, and then the if statement makes a judgment according to the user's choice, d means to execute the program segment labeled defrag, m Indicates that the program segment labeled mem is executed, and e represents the program segment labeled end is executed. At the end of each program segment, the program is jumped to the end label with goto end, and then the program will display good bye, and the batch operation ends. 
 
Fourth, the for loop command, as long as the conditions are met, it will execute the same command multiple times. 
 
Syntax: 
Execute a specific command for each file in a set of files. 
 
FOR %%variable IN (set) DO command [command-parameters] 
 
%%variable Specifies a single-letter replaceable parameter. 
(set) Specifies a file or set of files. Wildcards can be used. 
command specifies the command to execute on each file. 
command-parameters Specifies parameters or command-line switches for specific commands. 
 
For example, there is a line in a batch file: 
for %%c in (*.bat *.txt) do type %%c 
 
, the command line will display the contents of all files with bat and txt extensions in the current directory. 
 
 
Batch example 
 
1. IF-EXIST 
 
1) 
 
First create a test1.bat batch file in C:\ with Notepad, the content of the file 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 not, The batch 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 
this The result of running the command is the same as above. 
 
Description: 
(1) IF EXIST is used to test whether the file exists, the format is 
IF EXIST [path + file name] Command 
(2) %1 in the test2.bat file is a parameter, DOS allows 9 batch parameter information to be passed to Batch files, respectively %1~%9 (%0 represents the test2 command itself), which 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. 
 
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 " 
 
If you run: 
C:\>TEST3 ABC 
will display on the screen: 
XIAO 
TIAN 
XIN 
 
If you run: 
C:\>TEST3 AB 
will display 
XIAO 
TIAN 
 
on the screen During the execution of this command, DOS will assign an empty string to the parameter % 3. 
 
2. IF-ERRORLEVEL 
 
creates TEST4.BAT with the following contents: @ECHO 
OFF 
XCOPY C:\AUTOEXEC.BAT D:IF ERRORLEVEL 1 ECHO file copy failure 
IF ERRORLEVEL 0 ECHO successfully copy the file 
 
and then execute the file: 
C:\>TEST4 
 
If the file If the copy is successful, the screen will display "Successfully copy file", 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 value must be judged in descending order. So the following batch file is wrong: 
@ECHO OFF 
XCOPY C:\AUTOEXEC.BAT D:\ 
IF ERRORLEVEL 0 ECHO successfully copied file 
IF ERRORLEVEL 1 ECHO copied file not found 
IF ERRORLEVEL 2 ECHO The user aborts the copy operation through ctrl-c 
IF ERRORLEVEL 3 ECHO The preset error prevents the file copy operation 
IF ERRORLEVEL 4 ECHO The disk write error during the copy process 
 
No matter whether the copy is successful or not, the following: 
 
the copied file is not found  The
user uses ctrl-c Abort copy operation 
Preset error prevents file copy operation  All
disk write errors during copying 
 
will be displayed. 
 
The following are the return values ​​of several common commands and their meanings: 
backup 
0 backup succeeded 
1 backup file not found 
2 file sharing conflict prevented backup from completing 
3 user aborted backup with ctrl-c 
4 backup operation aborted due to fatal error 
 
diskcomp 
0 Disk comparison is the same 
1 Disk comparison is different 
2 The user aborted the comparison operation by ctrl-c 
3 The comparison operation was aborted due to a fatal error 
4 Preset error aborted the comparison 
 
diskcopy 
0 The disk copy operation succeeded 
1 Non-fatal disk read/write error 
2 The user passed ctrl- c end copy operation 
3 disk copy aborted due to fatal processing error 
4 preset error prevented copy operation 
 
format 
0 format successful 
3 The user aborted the formatting process through ctrl-c 
4 The formatting was aborted due to a fatal processing error 
5 At the prompt "proceed with format (y/n)?" the user typed n to end 
 
xcopy 
0 Successfully copied file 
1 Copy file was not found 
2 User aborts the copy operation through ctrl-c 
4 Preset error prevents file copy operation 
5 Write disk error during copying 
 
3. IF STRING1 == STRING2 
 
Create TEST5.BAT, the file content is as follows: 
@echo off 
IF "%1" == " A" format A: 
 
Execute: 
C:\>TEST5 
The content of whether to format the A: disk will appear on the A screen. 
 
Note: In order to prevent the parameter from being empty, the string is usually enclosed in double quotes (or other symbols, note that reserved symbols cannot be used). 
For example: if [%1]==[A] or if %1*==A* 
 
5. GOTO 
 
builds TEST6.BAT, the content of the file is as follows: @ECHO 
OFF 
IF EXIST C:\AUTOEXEC.BAT GOTO _COPY 
GOTO _DONE 
:_COPY 
COPY C:\AUTOEXEC.BAT D:\ 
:_DONE 
 
NOTE: 
(1) The label is preceded by an ASCII character colon ":", and there must be no space between the colon and the label. 
(2) The naming rules of labels are the same as those of file names. 
(3) DOS supports labels with a maximum of eight characters. When two labels cannot be distinguished, it will jump to the nearest label. 
 
6. FOR 
 
builds C:\TEST7.BAT, the content of the file is as follows: @ECHO 
OFF 
FOR %%C IN (*.BAT *.TXT *.SYS) DO TYPE %%C 
 
run:  After
C:>TEST7 is 
 
executed, on the screen It will display the contents of all files with extensions of BAT, TXT and SYS in the root directory of the C: drive (excluding hidden files).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325444436&siteId=291194637