Frequently-used commands echo, @, call, pause, and REM (TIPS: Use: instead of REM) are the most frequently-used commands for batch file processing. We started from them.
First, @ is not a command, but a special identifier for DOS batch processing. It is only used to block command line echo.
The following are some special tokens that may be seen in the doscommand line or batch processing:
Cr (0d) command line terminator
Escape (1B) ANSI Escape Character Guide
Space (20) Common parameter delimiters
Tab (09); = uncommon parameter delimiters
+ Copy command file Connector
*? File wildcard
"" String delimiter
| Command pipeline operator
<>>> File redirection
@ Command line echo Shield
/Parameter switch Guide
: Batch tag pilot
% Batch variable pilot
Second,: it can indeed play the role of REM annotation, and it is more concise and effective; but there are two points to note:
First, in addition to:, any character line starting with: is regarded as a label in batch processing, and all subsequent content is directly ignored, to distinguish it from a normal label, we recommend that you use a label that is not recognized by Goto, that is, a special symbol that is followed by a non-alphanumeric character.
Second, unlike REM, the following character lines are not displayed during execution, whether or not echo on is used to open the command line echo status, because the command interpreter does not regard it as a valid command line, Rem is more suitable than: In some cases. In addition, REM can be used in config. sys File.
Echo
Echo indicates the characters after this command
Echo off indicates that after this statement, all running commands do not show the command line itself @ and echo off, but @ is added at the beginning of each command line, it indicates that the command line of this line is not displayed during running (only the current line can be affected ).
ECHO Displays or hides the body of the batch processing program when the program is running. It can also be used to allow or disable command echo. The MS-DOS typically displays (ECHO) commands in the batch processing program on the screen when running the batch processing program. Use the echo command to disable this function. Syntax:
Echo [ON | off] [Message]
The on | off parameter specifies whether to allow command echo. To display the current echo settings, you can use the echo command without parameters. Message specifies the body for the MS-DOS to display on the screen.
Call
Call calls another batch file (if other batch files are called directly without calling, the current file cannot be returned and Subsequent commands of the current file will be executed after the batch file is executed)
Call calls another batch processing program from one batch processing program without suspending the first batch. Syntax:
Call [drive:] [path] filename [batch-parameters]
The [drive:] [path] filename parameter specifies the name and storage of the batch processing program to be called. The file name must use. BAT as the extension. Batch-parameters specifies the command line information required by the batch processing program.
Pause
Running pause will pause the execution of batch processing and display press any key to continue on the screen... prompt, wait for the user to press any key and then continue REM to indicate that the character after this command is interpreted line (comment), do not execute, just for your future reference (equivalent to the comments in the program ).
Pause suspends the execution of the batch processing program and displays a message prompting you to press any key to continue execution. You can only use this command in the batch processing program. Syntax:
Pause
Rem
Rem adds annotations to the batch file or config. sys. You can also use the REM command to block commands (you can also use semicolons in config. sys; instead of the REM command, but it cannot be replaced in batch files ). Syntax:
Rem [String]
The string parameter specifies the command to be blocked or the annotation to be included.
Example 1:
Edit. BAT file, enter the following content and save the disk as c: \. bat, after executing the batch processing file, you can: write all the files in the root directory into a.txt, start UCDOS, enter WPS and other functions.
The content of the batch file is: Command comment:
@ Echo off does not display subsequent command lines and current command lines
Dir c: \ *. *> a.txt: Write the C-drive file into a.txt.
Call c: \ UCDOS. Bat call UCDOS
Echo Hello show "hello"
Pause pause and wait for the button to continue
Rem prepare to run WPS Note: Prepare to run WPS
Cd ucdos enters the UCDOS directory
WPS running WPS
Batch File Parameters
The batch file can also use parameters (equivalent to the command line parameters of the doscommand) like C functions, which requires a parameter identifier "% ". % [1-9] indicates a parameter. A parameter is a string separated by spaces (or tabs) after the file name when a batch file is run. Variables can be changed from % 0 to % 9.% 0 indicates the Batch Processing Command itself. Other parameter strings are represented in the order of % 1 to % 9.
Example 2:
C: the root directory contains a batch of processing files named F. bat with the following content:
@ Echo off
Format % 1
If c: \> f a: is executed, F. in bat, % 1 indicates a:, so format % 1 is equivalent to format A:, so the above command is actually executed in format:
Example 3:
C: The processing file name in the root directory is T. bat, and the content is:
@ Echo off
Type % 1
Type % 2
Run c: \> T a.txt B .txt % 1: a.txt % 2: a.txt. Therefore, the command will display the contents of a.txt and B .txt in sequence.
===== Note ==========================
Parameters are also processed as variables in batch processing. Therefore, the percent sign is also used as the pilot character, followed by a number in 0-9 to form a parameter reference character. the relationship between the quote and the parameter (for example, the relationship between % 1 and A:) is similar to the relationship between the variable pointer and the variable value. to reference 11th or more parameters, you must move the start pointer of the DOS parameter. the shift command is acting as the pointer to move the starting pointer of the parameter to the next parameter, similar to pointer operations in C. the following figure shows the initial status,
CMDCommand 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% 9
After one shift, CMD cannot be referenced.
CMD arg1 arg2 arg3 arg4 arg5 arg6 arg7 Arg8 arg9 arg10
^
|
% 0% 1% 2% 3% 4% 5% 6% 7% 9
After two shifts, arg1 is also deprecated, and % 9 points to null, with no reference significance.
CMD arg1 arg2 arg3 arg4 arg5 arg6 arg7 Arg8 arg9 arg10
^
|
% 0% 1% 2% 3% 4% 5% 6% 8
Unfortunately, both Win9x and DOS do not support shift inverse operations. shift supports the/n parameter only in the NT kernel command line environment. You can use the first parameter as the benchmark to move the start pointer.
======================================
The special command if goto choice for is a relatively advanced command in the batch processing file. If you are familiar with these commands, you are an expert in batch processing files.
I. If
If is a condition statement used to determine whether the specified conditions are met and then 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 indicates unequal, the same below), the condition is true. Run the command; otherwise, run the next sentence.
For example:
If "% 1" = "A" format:
==========================================
If [not] string1 = string2 command has the following notes:
1. Double quotation marks containing strings are not required by syntax, but are used to being an "anti-DDoS" character.
2. string1 is not necessarily a parameter. It can also be an environment variable, a loop variable, or
OthersString constants or variables
3. Command is not required by syntax. string2 can be followed by a space to form a valid command line.
==================================
2. If [not] exist [path \] command to be executed in the file name
If a specified file exists, the condition is true. Run the command. Otherwise, run the next sentence. For example:
If exist c: \ config. sys Type C: \ config. sys indicates that if the c: \ config. SYS file exists, its content is displayed.
==========================================
You can also use the following:
If exist command device is a device that has been attached to 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 $
SoftwareThe environment varies slightly. When using these device names, make sure that the following three items are met:
1. This device exists (except for devices virtualized by software)
2. the device driver has been loaded (standard devices such as aux and PRN are defined by the system default)
3. the device is ready (mainly A: B :..., com1 ..., lpt1... you can run the MEM/d | find "device"/I command to review the devices loaded in your system.
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 devices and files use handle) the handle is the name, similar to the file name, but is not applied to disk management, but to memory management. The so-called device loading also refers to allocating a reference handle to it in the memory.
======================================
3. If errorlevel <number> command to be executed
Many DOS Programs return a numeric value to indicate the result (or status) of the program running after the execution ends. The if errorlevel command can be used to determine the return value of the program, different commands are executed based on different return values (the return values must be sorted in ascending order ). If the return value is equal to the specified number, the condition is true. Run the command. Otherwise, run the next sentence. For example:
If errorlevel 2 goto X2
==========================================
It is not necessary to sort the returned values in ascending order, but it is a customary usage when the command is executed as Goto. When the SET command is used as the command to execute, it is usually arranged in ascending order, for example, you need to place the return code in the environment variable in the following order:
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, you can also use the following loop to replace it. The principle is the same:
For % E in (1 2 3 4 5 6 7 8...) do if errorlevel % E set El = % E
For more efficient and concise usage, refer to another article I wrote about how to obtain errorlevel. The reason for this phenomenon is that if errorlevel compares the return code's judgment conditions is not equal, it is greater than or equal. due to the redirection feature of Goto, sorting from small to large will cause a jump out of a small return code. Due to the "repeated" value assignment feature of the set command, sorting from large to small causes a smaller return code to overwrite a larger return code. in addition, although if errorlevel = <number> command is also a valid command line, command.com only interprets the command line as a command line splitter and ignores it.
======================================
Ii. Goto
When the Goto batch file runs here, it will jump to the label specified by Goto (label, which is defined by the standard string). The GOTO statement is generally used with the if statement, execute different command groups according to different conditions. For example, the Goto end: End echo this is the end label is defined by ": string". The row where the label is located is not executed.
==========================================
Label is often translated as "label", but this is not widely agreed. goto and: this function can be used in combination to achieve a jump in the middle of the execution. Combined with if, the conditional branches of the execution process can be implemented, and multiple if statements can be grouped, similar to the switch case structure in C or the select case structure in basic, large-scale and structured command groups can implement functions in advanced languages. the following is a comparison between the syntax structure of batch processing and C/basic: Batch C/basic goto &: & if {} & else {}/IF & elseif & endif goto &: & if... switch & case/select case goto &: & if & set & envar... function ()/function (), sub () ======================================
3. Choice
Choice uses this command to allow the user to enter a character (used for selection), so that different errorlevels are returned based on the user's choice, and then run different commands according to the user's choice in combination with if errorlevel.
Note: Choice commands are external commands provided by DOS or windows. the syntax of choice commands of different versions is slightly different. Use choice /? View usage.
Choice command syntax (this syntax is the syntax of the choice command in Windows 2003, the syntax of choice in other versions is similar to this ):
Choice [/C choices] [/n] [/CS] [/T timeout/d choice] [/M text]
Description: This tool allows you to select a project from the selection list and return the selected index.
Parameter List:/C choices specifies the list of options to be created.
The default list is "YN ". /N hide the Option List at the prompt. The preceding message is displayed, and the option is still enabled.
/CS allows you to select the case sensitivity option. By default, this tool is case-insensitive.
/T timeout specifies the number of seconds before the default value is set. The acceptable value ranges from 0 to 9999. If 0 is specified, no pause is performed. The default option is selected.
/D choice: Specify the default option after NNNN seconds.
The characters must be in the selection of a group specified by/C;
At the same time, you must use/t to specify the NNNN.
/M text specifies the message to be displayed before the prompt. If not specified, only the prompt is displayed.
/? Displays help messages.
Note: The errorlevel environment variable is set to the key index selected from the selection set. Returns 1 for the first selection, 2 for the second selection, and so on. If the key you press is not a valid choice, the tool generates a warning. If the tool detects an error, it returns the errorlevel value of 255. If you press Ctrl + break or Ctrl + C, the tool returns the errorlevel value of 0. When the errorlevel parameter is used in a batch program, the parameters are sorted in descending order.
Example:
Choice /? For choice/c ync/m ", Press Y, N, or C. "
Choice/T 10/c ync/CS/d y choice/c AB/M "option 1 select a, option 2 select B. "
Choice/c AB/N/m "option 1 select a, option 2 select B. "
============================================
I listed the usage help for choice under Win98, which has been differentiated
Waits for the user to choose one of a set of choices. Wait for the user to select one of the characters to be selected
Choice [/C [:] choices] [/n] [/S] [/T [:] C, NN] [text]/C [:] choices specifies allowable keys.
Default is YN specifies the allowed buttons (to be selected). The default value is YN/n do not display choices and? At end of prompt string. The question mark and the character to be selected are not displayed.
/S treat choice keys as case sensitive. sensitive when processing the characters to be selected
/T [:] C, nn default choice to C after NN seconds, the prompt string errorlevel is set to offset of key user presses in choices is selected by default after C text prompt string to display. errorlevel is set to the offset value of the characters typed by the user in the characters to be selected if I run the command:
For choice/c ync/m ", Press Y, N, or C. "
The screen will show: Press Y to confirm, press n to confirm, or press C to cancel. [Y, N, C]?
For example, the content of test. bat is as follows (NOTE: When determining the return value using if errorlevel, sort the returned values from high to low ):
@ Echo off choice/C dimethyl/M "defrag, mem, end" I
F 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]? ", The user can select d m e, and then the if statement makes a judgment based on the user's choice. D indicates the program segment with the execution label as defrag, and M indicates the program segment with the execution label as mem, E indicates the program segment whose execution label is "end". Each program segment finally jumps the program to the end label with "Goto end", and the program displays "good bye". The batch processing is completed.
IV.
Loop Command, as long as the condition is met, it will execute the same command multiple times. Syntax: execute a specific command on each file in a group of files.
For % variable in (SET) do command [command-parameters] % variable
Specifies a single letter replaceable parameter. (SET) specifies one or more files. Wildcard characters can be used. Command specifies the Command executed on each file. Command-parameters specifies a parameter or command line switch for a specific command. For example, a batch file contains one row:
For % C in (*. bat *. txt) do type % C
The command line displays the contents of all files with the bat and TXT extensions in the current directory.
It should be noted that when the string in () is not a single or multiple file names, it will simply be replaced as a string. This feature is added () can be embedded into multiple strings. Obviously, 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 command output or strings in the file, many switches are also used to extend the file replacement function.
Batch Processing example
1. If-exist
1) First, use NotePad to create a test1.bat batch file in c: \. 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 c: \ autoexec. BAT file exists, its content will be displayed. If it does not exist, the batch processing will prompt you that the file does not exist.
2) create another test2.bat file with the following content:
@ Echo off if exist \ % 1 Type \ % 1
If not exist \ % 1 echo \ % 1 does not exist
Run: C: \> Test2 autoexec. bat. The command runs the same result as above.
Note:
(1) If exist is used to test whether a file exists. The format is
If exist [path + file name] command
(2) % 1 in the test2.bat file is a parameter. Dos allows passing nine batch parameter information to the batch processing file, which is % 1 ~ % 9 (% 0 indicates the Test2 command itself), which is a bit like the relationship between real parameters and parameters in programming. % 1 is the form parameter, and autoexec. bat is the real parameter.
==========================================
DOS does not have the limit of "allow Passing 9 batch parameter information". The number of parameters is limited only by the length of the command line and the processing capability of the called command. however, in the batch processing program, we can only reference 10 parameters at the same time, because D
OS only provides % 0 ~ % 9.
======================================
3) 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 displays: Xiao Tian Xin
If you run: C :\> test3 A B
The screen displays Xiao Tian. During the command execution, DOS will specify an empty string to the 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, the file is successfully copied.
Then execute the file:
C: \> test4
If the file is successfully copied, the screen displays "successfully copied file"; otherwise, the screen displays "failed file copy ". If errorlevel is used to test the return value of the previous DOS command,
Note: It is only the return value of the previous command, and the return value must be determined in ascending order. Therefore, the following batch file is incorrect:
@ Echo off xcopy c: \ autoexec. Bat D :\
If errorlevel 0 ECHO, the file is successfully copied.
If errorlevel 1 ECHO does not find the copy object
If errorlevel 2 ECHO, the user uses Ctrl-C to stop the copy operation.
If errorlevel 3 Echo preset Error Blocking file copy operation
If errorlevel 4 echo disk write error during copy process
No matter whether the copy is successful or not, the following information is displayed: if the copy object is not found, the user uses Ctrl-C to stop the copy operation preset error to prevent the file copy operation from writing disk errors during the copy operation. The return values of several common commands and their meanings are as follows:
Backup
0 successfully backed up
1 backup file not found
2. File Sharing conflicts prevent backup from being completed
3. Use Ctrl-C to stop the backup.
4. the backup operation is aborted due to a fatal error.
Diskcomp
0 disks are the same
1 disk is different
2. You can use ctrl-C to stop the comparison operation.
3. The comparison operation is aborted due to a fatal error.
4 preset error abort comparison
Diskcopy
0 disk copy operation successful
1 non-fatal disk read/write error
2. You can use ctrl-C to end the copy operation.
3. the disk copy is aborted due to a fatal processing error.
4. The copy operation is blocked due to a preset error.
Format
0: formatted successfully.
3. Use Ctrl-C to stop formatting.
4. The format is aborted due to a fatal processing error.
5. When the message "Proceed with format (y/n )? "End with user type N
Xcopy
0 successfully copied the file
1 copy file not found
2. You can use ctrl-C to stop the copy operation.
4. preset errors prevent file copy operations
5. An error occurred while writing the disk during the copy process.
Chkdsk
0: no error found
255 locate one or more errors
Choice
0. Press Ctrl + C/break.
1. the user presses the first key.
255 the error conditions in the command line are detected.
Position of valid characters pressed by other users in the list
Defrag
0 fragment compressed successfully
1 Internal error
2. There is no empty cluster on the disk. To run defrag, at least one empty cluster is required.
3. the user uses Ctrl + C to exit defrag.
4. General errors
5 defrag errors when reading the Cluster
6. defrag encountered an error when writing the Cluster
7. An error occurred while allocating space.
8 Memory Errors
9 there is not enough space to compress disk fragments
Deltree
0 successfully deletes a directory
Diskcomp
0. The two disks are the same.
1. Different
2. Press Ctrl + C to terminate the comparison.
3. Serious Error
4. initialization error
Find
0. The query is successful and at least one matching string is found.
1. The search is successful but the matching string is not found.
2. An error occurred while searching.
Keyb
0. The keyboard definition file is successfully loaded.
1. An invalid keyboard code, character set, or syntax is used.
2. the keyboard definition file is broken or not found.
4. An error occurred while communicating with the keyboard and monitor.
5. The required character set is not ready
Move
0 successfully moved the specified file
1. An error occurred.
Msav/n
86 virus detected
Replace
0 replace successfully replaces or adds a file
1 MS-DOS version and replace incompatible
2 replace cannot find the source file
3 replace cannot find the source or target path
5. You cannot access the file to be replaced.
8. Unable to execute replace due to insufficient memory
11 command line syntax error
Restore
0 restore successfully restored the file
1. the file to be restored cannot be found in Restore.
3. Press Ctrl + C to terminate the restoration process.
4. Restore terminated due to an error
Scandisk
0 Scandisk does not detect any errors on the drive it checks
1. Because the command line syntax is incorrect, Scandisk cannot be run. 2. Scandisk stops unexpectedly due to memory exhaustion or internal errors. 3. When the user asks Scandisk to exit midway through 4, the user decided to exit 254 Scandisk in advance to find the disk fault, and all corrections have been made to 255 Scandisk to find the disk fault, but not all corrections
Setver
0 setver successfully completed Task 1 the user specified an invalid command switch 2 the user specified an invalid file name 3 the user did not have enough system memory to run the command 4 the user specified an invalid version Number Format 5 setver the specified item 6 setver not found setver in the version table. EXE file 7 the user specified an invalid drive 8 the user specified too many command line parameters 9 setver detected the loss of command line parameter 10 reading setver. during the EXE file, setver detected an error 11 setver. the specified setver. the EXE file does not support version 13 versions. Table 13 does not have enough space to store new items. setver detects an error in the EXE file
3. If string1 = string2
Create test5.bat. The file content is as follows:
@ Echo off if "% 1" = "A" format:
Run:
C: \> test5
Whether to format the: disk is displayed on the screen.
Note: To prevent the parameter from being empty, double quotation marks (or other symbols) are generally used to enclose the string. For example:
If [% 1] = [a] Or if % 1 * = A * 5,
Goto
Create test6.bat. The file content is as follows:
@ Echo off if exist c: \ autoexec. Bat goto _ copy goto _ done
: _ Copy Copy c: \ autoexec. Bat D :\
: _ Done
Note:
(1) The colon Before the label is an ASCII character ":", there must be no space between the colon and the label.
(2) The naming rules for labels are the same as those for file names.
(3) DoS supports a maximum of eight characters. When two labels cannot be distinguished, the system redirects to the nearest one.
==========================================
1) label is also called label)
2) labels cannot start with most non-alphanumeric characters, but can be used in file names.
3) when there is no difference between the two tags, the tag will jump to the top of the position
======================================
4.
Create c: \ test7.bat. The file content is as follows:
@ Echo off for % C in (*. bat *. txt *. sys) do type % C
Run:
C: \> test7
After the command is executed, all files with the extension bat, txt, and sys in the C: root directory are displayed on the screen (excluding hidden files ).
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.