Bat Batch File Syntax (1)

Source: Internet
Author: User
Tags switch case
Files with the extension BAT (or CMD in NT/2000/XP/2003) are batch files.

===== Gjr note ========================================== =====
. Bat is a batch processing file under DOS
. CMD is another type of batch file in the NT kernel command line environment.
In a broader sense, Unix shell scripts, as well as other operating systems, and even the text that is interpreted and executed by the shell in applications, all play a very similar role as batch files, it is also interpreted and executed by a dedicated interpreter in the unit of action. This text form is more commonly referred to as the scripting language. Therefore, to a certain extent, batch, Unix shell, awk, basic, Perl, and other script languages are the same, except that the scope of application and interpretation platforms are different. Even some applications still use batch processing, and their content and extensions are completely different from those of DOS batch processing.
==========================================

First, the batch processing file is a text file. Each line of this file is a DOS command (most of the time it is like the command line we run at the DOS prompt ), you can use any text file editing tool such as edit in DOS or notepad in Windows to create and modify batch files.

===== Gjr note ===============================
Non-DOS commands can be used in batch files, or even common data files that do not have executable features. This is due to the involvement of the new interpretation platform, windows, this makes batch processing applications increasingly "marginalized ". Therefore, the batch processing we discuss should be limited to the DoS or command line environment. Otherwise, many concepts and settings must be relatively large.
======================================

Second, the batch processing file is a simple program that can control the command running process through the conditional statement (IF) and flow control statement (goto, you can also use the for statement to execute a command cyclically in batches. Of course, the programming capability of batch processing files is very limited than that of C language and other programming statements, and it is also very nonstandard. The program statements for batch processing are several DOS commands (including internal commands and external commands). The batch processing capability depends on the commands you use.

========================================
The batch file can also be called the batch program, which is different from the compiled language. In C language, files with the extension of C or CPP can be called C language files or C language source code files, but only compiled and connected EXE files can be called C language programs. Because batch files are both readable and executable, the boundaries of these titles are vague.
======================================

Third, each written batch processing file is equivalent to a DoS external command. You can put the directory in your dos search path) so that it can run in any location. A good habit is to create a bat or batch directory (such as C:/batch) on the hard disk, and then put all the batch files you have written into this directory, in this way, you only need to set C:/batch in the path, and you can run all your batch processing programs at any location.

===== Note ======
In the case of a DOS system, the executable program can be divided into five sub-categories. The execution priorities are: doskey macro commands (pre-resident memory), command. internal commands in COM (in memory at any time according to the memory environment), executable programs with the COM Extension (directly loaded into memory by command.com ), executable programs with exe extensions (loaded into memory after command.com is relocated), and batch processing programs with BAT extensions (analyzed by command.com, according to the content in the order of priority to call the 2, 3, 4, 5 executable programs, analysis of a row, execute a line, the file itself does not load into memory)
================

Fourth, in DOS and Win9x/me systems, C: autoexec under the root directory. bat batch files are automatically run batch files. Each time the system starts, the files are automatically run. You can put the commands to be run every time the system starts, for example, you can set the search path, call the mouse driver and disk cache, and set system environment variables. The following is an example of autoexec. Bat running on 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 the automatic Run batch file of the DOS system, which is interpreted and executed when command. com is started;
In the Win9x environment, dosstart is supported. bat, winstart. BAT and many other batch files that run automatically. bat is also added. DOS. w40. bak. old. PWS and many other variants to adapt to complex environments and changing needs.
===== Willsort compilation ==================
The following are many examples of command classification. In Common commands, @ is not a command, but Dir, copy, and other frequently-used commands are not included. In special commands, all commands are common commands for me. We recommend that you divide the commands referenced by batch processing into three types: Internal commands, external commands, and third-party programs. The other types of internal commands and external commands are dedicated or commonly used in batch processing. They can be called "batch processing commands ".

The following excerpt from the MS-DOS 6.22 help document on the "batch command" text, of course, some of the concepts and definitions are somewhat behind.

Batch Processing Command

A batch file or batch program is a body file containing several MS-DOS commands with the extension. bat. When you type the name of the batch processing program at a command prompt, The MS-DOS runs the commands in this batch in groups.

Any command that can be used in a command prompt can be used in a batch processing program. In addition, the following MS-DOS commands are specifically used in batch processing programs.
============

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

===== Gjr 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.

==== Gjr choreographer

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

===== Gjr choreographer ====================================
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.

===== Gjr choreographer ====================================== ==============================
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.
========================================================== ======================================

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.