Bat. file command syntax

Source: Internet
Author: User
Tags echo command file copy switch case

Common commands

Echo, @, call, pause, and REM (TIPS: Use: instead of REM) are several of the most common commands for batch file processing. We started from them.

===== Note ==============
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 indicates the characters after this command
Echo off indicates that after this statement, all running commands do not display the command line itself.
@ Is similar to echo off, but it is added at the beginning of each command line, indicating that the command line of this line is not displayed at run time (only the current line can be affected ).
Call calls another batch file (if you directly call another batch file without calling it, you will not be able to return the current file and execute subsequent commands of the current file after the batch file is executed ).
Running pause will pause the execution of 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 indicates that the character after this command is interpreted as a line (comment). If it is not executed, it is only used for future reference (equivalent to a comment in the program ).
===== Note ======
The description here is confusing. It is better to reference the command line of a command to make it more organized.

-------------------------
Echo

When the program is running, the body of the batch processing program is displayed or hidden. 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]

If you want to use the echo command to display a command, you can use the following syntax:

Echo [Message]

Parameters

On | off
Specifies whether to allow command echo. To display the current echo settings, you can use echo without parameters.
Command.

Message
Specifies the body of the MS-DOS to display on the screen.

-------------------

Call

Calling another batch processing program from one batch processing program will not result in the suspension of the first batch processing.

Syntax

Call [drive:] [path] filename [batch-parameters]

Parameters

[Drive:] [path] filename
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

Pause the execution of the batch processing program and display a message prompting you to press any key to continue execution. Only in batch
Program.

Syntax

Pause

Rem

Add annotations to the batch file or config. sys. You can also use the REM command to shield the command (in config. sys
You can also use semicolons (;) instead of the REM command, but it cannot be used in batch files ).

Syntax

Rem [String]

Parameters

String
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 you execute C:/> f:
When F. bat is executed, % 1 indicates a:. In this way, format % 1 is equivalent to format A:. Therefore, the preceding Command actually runs format:

Example 3: C: the name of the processing file under the root directory is T. bat, and the content is:
@ Echo off
Type % 1
Type % 2

Run C:/> T a.txt B .txt.
% 1: paia.txt
% 2: Invalid B .txt
The following command displays the.txt and B .txt files 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 figure is as follows:

Initial status. CMD is the command name and 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.
========================

Special commands

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.

1. 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.

Example: If "% 1" = "A" format:

====

The Command Line Help of if describes the following points:
If [not] string1 = string2 command
Note the following points:
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 another String constant or variable.
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.

* ***** Note ********
You can also use the following:
If exist command
Device is a device that has been loaded in the dossystem. 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 varies slightly depending on the hardware and software environment. When using these device names, you must ensure the following three points:
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

===== Note ==============
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 getting errorlevel.

The cause of this phenomenon is that the judgment condition of if errorlevel comparison return code is not equal to, but 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.
======================================

2. When the Goto batch processing 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:

Goto end

: End
Echo this is the end

The label is defined by ": string". The row where the label is located is not executed.

==== Willsort Compilation

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 &: goto &:
Goto &: & if {} & else {}/IF & elseif & endif
Goto &: & if... switch & case/select case
Goto &: & if & set & envar... function ()/function (), sub ()
========================================
3. Choice uses this command to allow the user to enter a character (used for selection), and return different errorlevels based on the user's selection, and then works with if errorlevel, run different commands according to your choice.

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 index of the selected project.

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,
The option is still enabled.

/CS allows you to select the case sensitivity option. By default, this tool
It is case-insensitive.

/T timeout specifies the number of seconds before the default value is set. The acceptable value is from 0.
Up to 9999. If 0 is specified, there will be no pause. the default option is
Select.

/D choice: Specify the default option after NNNN seconds. The character must be in/C
You must specify the NNNN with/t.

/M text specifies the message to be displayed before the prompt. If not specified, the tool only
A prompt is displayed.

/? Displays help messages.

Note:
The errorlevel environment variable is set to the key index selected from the selected set. The first option to be listed
Returns 1, returns 2, 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 255
Errorlevel value. If you press Ctrl + break or Ctrl + C, the tool returns 0
The errorlevel value. When the errorlevel parameter is used in a batch program
Sort in sequence.

Example:
Choice /?
For choice/c ync/m ", Press Y, N, or C. "
Choice/T 10/c ync/CS/d y
Select a for choice/c AB/M "option 1 and B for option 2. "
Choice/c AB/N/m "option 1 select a, option 2 select B. "

===== Willsort compilation ==================================
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 group of 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 characters to be selected are not displayed.
/S treat choice keys as case sensitive.
Process lowercase sensitive characters to be selected
/T [:] C, NN default choice to C after NN seconds
C is selected by default after NN seconds
Text prompt string to display
The prompt string to be displayed.
Errorlevel is set to offset of key user presses in choices.
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: choice/c ync/M "OK, Press Y, N, or cancel to press C. "
The screen displays:
Press Y to confirm, N to confirm, or 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"
If errorlevel 3 goto end
If errorlevel 2 goto mem
If errorlevel 1 goto defrag

: Defrag
C:/DOS/defrag
Goto end

: Mem
Mem
Goto end

: End
Echo good bye

After this batch is run, "defrag, mem, end [d, M, E]? ", 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.

4. The for loop command will execute the same command multiple times as long as the conditions are met.

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
Specify parameters or command line switches for specific commands.

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.

===== Willsort compilation ======================================== ==============================
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:/file contains the autoexec. BAT file, 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.

===== Willsort compilation ======================================== ==============================
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, only 10 parameters can be referenced at the same time, because dos only gives % 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
Displayed on the screen
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 that it is only the return value of the previous command, and the return value must be determined in order from large to small.
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

Whether the copy is successful or not, the following:

Copy file not found
You can use ctrl-C to stop the copy operation.
Preset errors prevent file copy operations
An error occurred while writing the disk during the copy process.

Are displayed.

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 users

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.