Bat batch processing command usage practical tutorial

Source: Internet
Author: User
Tags echo command

Bat batch processing command usage practical tutorial

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

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

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.

 

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:

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.

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

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.

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

 

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]?" is displayed. 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.

 

Batch Processing example

1. If-exist

1)

First, use NotePad to create a test1.bat batch file in C: //. The file content 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 autoexec. Bat 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.

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 "file copy failed ".

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 "Proceed with format (y/n)?" is displayed )?" End with user input 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 ).

Use of the bat command

.

1. Introduction to simple batch processing internal commands

 

1. Echo command

Enable or disable the request echo function or display messages. If no parameters exist, the echo command displays the current echo settings.

Syntax

Echo [{on off}] [Message]

Sample: @ echo off/ECHO Hello World

In actual application, we will combine this command with the redirection symbol (also known as the pipeline symbol) to input some commands to a file in a specific format. this will be reflected in future examples.

2. @ command

The command after @ is not displayed. In the intrusion process (for example, you can use batch processing to format the enemy's hard disk), the other party cannot see the command you are using.

Sample: @ echo off

@ ECHO now initializing the program, please wait a Minite...

@ Format X:/Q/u/AutoSet (the/y parameter cannot be used for the format command. Fortunately, Microsoft has reserved the AutoSet parameter for us, the effect is the same as that of/Y .)

3. Goto command

Specify to jump to the tag. After the tag is found, the program processes the commands starting from the next line.

Syntax:

Goto label (label is a parameter that specifies the rows in the batch processing program to be switched .)

Sample:

If {% 1 }={} goto noparms

If {% 2 }={} goto noparms (if you do not understand the IF, % 1, and % 2 here, skip the step first, which will be explained in detail later .)

@ REM check parameters if null show usage

: Noparms

Echo usage: monitor. Bat serverip portnumber

Goto end

The name of a tag can start at will, but it is better to have a meaningful letter. Add a letter before it to indicate that the letter is a tag. The Goto command is based on this: to find the next step and jump to it. It is better to have some explanations so that others seem to understand your intention.

4. Rem command

The annotation command is equivalent to/* -------- */in the C language. It is not executed, but serves as a comment for others to read and modify.

Rem message

Sample: @ REM here is the description .?

????? 5. Pause command

When running the pause command, the following message is displayed:

Press any key to continue...

Sample:

@ Echo off

: Begin

Copy A: *. * D: // back

Echo please put a new disk into driver

Pause

Goto begin

In this example, all files on drive a are copied to drive D: // back. When the displayed note prompts you to put another disk into drive a, the pause command will suspend the program so that you can change the disk and press any key to continue processing.

6. Call Command

Call another batch processing program from one batch processing program without terminating the parent batch processing program. The Call Command accepts the labels used as the call target. If a call is used outside a script or batch file, it does not work in the command line.

Syntax

Call [[drive:] [path] filename [batchparameters] [: Label [arguments]

Parameters

[Drive:} [path] filename

Specifies the location and name of the batch processing program to be called. The filename parameter must have the. bat or. CMD extension.

7. Start command

Call an external program. All the DOS commands and command line programs can be called by the START command.

Common Intrusion parameters:

Minimum window size when Min starts

Separate starts a 16-bit windows program in a separate space

High starts applications in the high priority category

Realtime starts applications in the realtime priority category

Wait starts the application and waits for it to end

Parameters: these are parameters sent to the command/program.

When the executed application is a 32-bit GUI application, cmd. EXE returns a command prompt before the application is terminated. If it is executed in the Command Script, the new behavior will not occur.

8. Choice command # This command will not be used yet. Search for information online #

Choice uses this command to allow users to enter a single character to run different commands. The/C: parameter should be added for use, and C: should be followed by a prompt to enter characters without spaces. Its return code is 1234 ......

For example: choice/C: dimethyl defrag, mem, end

Will display

Defrag, mem, end [d, M, E]?

Sample:

The content of sample. bat is as follows:

@ Echo off

Choice/C: dimethyl defrag, mem, end

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.