BAT file syntax and techniques (batch file or batch Program)

Source: Internet
Author: User
Tags file copy

 

BAT (batch file or batch program) File Syntax and skills

First, the batch processing file is a text file. Each line of the text file is a DOS command.

Second, the batch processing file is a simple program. You can use if and goto to control the process and for to execute a command cyclically.

Again: A compiled batch processing file is equivalent to a DoS external command, that is, as long as you store the BAT file

If the directory is set on the path, CMD can execute the BAT file at any location.

Finally, the C-drive root directory runs automatically first to the autoexec. bat batch file, which is automatically run every time the system starts,

We can write some frequently used software to the BAT file to avoid opening the software one by one.

Finally, the role of batch processing is to automatically execute multiple commands consecutively. the BAT file is readable and executable.

Example: The following is a simple test. BAT file.

@ Echo off

E:

Dir

D:/java_world/eclipse-jee-europa-fall-win32/Eclipse/eclipse.exe

Pause

The bat should do the following: First switch to the edisk, then limit the files under the edisk, and finally start eclipse, and finally stay on the CMD interface.

Common commands for BAT files:

1 ECHO: The character after this command is displayed

2 echo off: After this statement, all running commands do not display the command line itself

3 @: this command is similar to echo off, indicating that the command line is not displayed during running (which affects the current line)

4 call: call another batch processing file (if call is not required, the execution of another bat file will not return to the current file after execution)

5 pause: When this sentence is run, it will be paused in the CMD window and display press any key to continue... press any key to continue executing the command

6 REM: comments, not executed, just for your reference in the future (Tip: You can use: instead of REM flood)

BAT file Parameters

The batch file can use parameters like the C language (equivalent to the command line parameters of the doscommand), which requires a parameter identifier %

Parameters can be % 1 to % 9 (Note: % 0 indicates the BAT file itself). Multiple parameters are separated by space or tab.

Example:

Assume that the content of drive F: test. bat is as follows:

@ Echo off

Type % 1

Type % 2

Then, go to CMD and switch to drive F:/> text a.txt B .txt

Then a.txt will be passed to % 1 B .txt and % 2, and the command will show a.txt and B .txt in sequence.

Special commands for BAT files

If, Goto, choice, for is advanced. If you are familiar with it, I will call you expert.

I. If condition statements are used to determine whether they comply with the rules. There are three formats:

1. If [not] "parameter" = "string": command to be executed (note: the command to be executed is in this line)

Meaning: the parameter is equal to [not equal to (not indicating not)] the specified string. Run the command. Otherwise, run the next command.

2. If [not] exist [path/] File Name: command to be executed (note: the command to be executed is in this line)

Example: If exist C:/config. sys Type C:/config. sys

Description: If drive C has config. sys, its content is displayed.

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.

Example: If errorlevel 2 goto X2

Ii. Goto

The Goto command is used to jump to the specified label. (The label is defined by a colon (:) followed by a standard string.) The GOTO statement is generally used together with the if statement to execute different command groups according to different conditions.

Example: goto end

: End (Note: The label format is ": string". The row where the label is located is not executed)

Echo this is the end

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 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, 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, there will be no pause. the default option is

Select.

/D choice: Specify the default option after NNNN seconds. The characters must be in the selection of a group specified by the/C option, and the/T must be used 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 selected set. Returns 1 for the first choice listed, 2 for the second choice, 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

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

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 errotlevel 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 using goto end. Then, the program displays Good bye, And the batch processing is completed.

4. For Loop Command, as long as the conditions are met, it will execute the unified 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.

Below are a few examples of BAT:

1. If-exist creates 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 this 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. 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.

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 * = *

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.

6.

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)

 

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.