BAT Batch File Syntax page 1/2

Source: Internet
Author: User
Tags echo command switch case

Files with the extension bat (or cmd in nt/2000/xp/2003) are batch files.
. 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.
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 (for example, C: \ BATCH) on the hard disk, and then put all the batch files you have compiled 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 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:
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
Then 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 &: & 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.

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.