Common batch processing Internal command use detailed _dos/bat

Source: Internet
Author: User
Tags current time echo command extend goto

Batch definition: As the name suggests, a batch file is a series of commands that are set up in a certain order as an executable text file with the extension bat or cmd. These commands are collectively referred to as batch commands.

Little knowledge: You can press CTRL + C on the keyboard to force a batch to terminate the execution process.

After knowing the general meaning, we began to learn. Look at a simple example first!

@echo off
echo "Welcome to the very bat!"
Pause

Save the above 3 commands as files Test.bat or Test.cmd and then execute,
He would show the following two jargon on the screen:

Welcome to the very bat!
Please press any key to continue ...

This is a simple batch file, and this batch file uses 2 Commands "echo" and "pause" and a special symbol "@"
From the simple batch above, we can see that batch processing is a combination of some symbols with special meaning and some commands to complete the specified function, so how many of these special symbols and function commands are there in batch processing? Now let's take a closer look at some of the most commonly used!
(The following content source network, please read carefully, good to go to the following section of the example description)
======================================================
Common commands for batches (more commands are not listed, please refer to help)
1. REM and::
2, ECHO and @
3, PAUSE
4, ERRORLEVEL
5. TITLE
6, COLOR
7, Mode configuration system equipment
8, GOTO and:
9, find
10, START
11, Assoc and Ftype
12, pushd and POPD
13, call
14, shift
15, IF
16, setlocal and variable delay
17, ATTRIB Display or change file properties

Introduction command

1. REM and::

REM is an annotation command that is generally used to annotate the program, and the content after the command is not executed but can be returned.
Secondly,:: Can also play a role in the annotation of REM, and more concise and effective; But there are two points to note:

First, any word rows that begins with a colon is treated as a label in a batch and ignores all of the contents immediately thereafter.
Valid label: The colon is followed by a string that begins with an alphanumeric character, which can be identified by a goto statement.
Invalid label: After the colon followed by a non-alphanumeric special symbol, goto unrecognized label, can play a role in annotation, so:: Often used as annotation symbol, in fact: + can also play a role in annotation.

Second, unlike REM,: the character rows does not echo when it is executed, regardless of whether the command line Echo state is opened with Echo on, because the command interpreter does not consider him to be a valid command line, so rem, in some cases, will be more applicable than: In addition, REM can be used in Config.sys files.

In-line annotation format:% comment content% (not commonly used, use caution)

2, ECHO and @

The @ character closes the command before it is placed on the command, regardless of whether the echo is open at this time.
The functions of the Echo command are listed as follows:

(1) Turn on echo or turn off echo feature
Format: Echo [{On|off}]
If you want to turn off the display of the ECHO off command line itself, you need to precede the command line with "@".

(2) Display the current ECHO setting state
Format: Echo

(3) Output hint information
Format: ECHO information content
These are the three common uses of the echo command, which are familiar and available, but you should also know the following tips as a DOS command miner:

(4) Turn off the DOS command prompt
Type echo off at the DOS prompt to turn off the display of the DOS prompt so that the screen leaves only the cursor until you type echo on and the prompt will appear again.

(5) Output blank line, which is equivalent to enter a carriage return
Format: ECHO.
It is important to note that in the command line. "There must be no spaces in the middle of the echo, otherwise". "will be output to the screen as a cue message. In addition ". "may use,:;"/[\]+, such as any symbol substitution.
Command echo. The output of the carriage return, through the DOS pipe steering can be used as the input of other commands, such as echo.| Time is equivalent to giving a carriage return after the time command executes. So the system automatically returns to the DOS prompt after the current time is displayed

(6) Questions in the answer order
Format: ECHO Reply | command file name
The above format can be used to simplify the operation of a number of man-machine conversation commands (such as: Chkdsk/f;format Drive:;del *.*), which is the input to the Man-machine conversation command using the preset reply of the echo command output via the DOS pipe command. The following example is equivalent to entering "Y" carriage return when the calling command has a man-machine conversation:
C:>echo y| chkdsk/f
C:>echo y| DEL A:*. *

(7) Create a new file or add the contents of the document
Format: ECHO file content > FileName
ECHO file content >> filename
For example:
C:>echo @ECHO off>autoexec. BAT set up automatic batch processing file
C:>echo c:\cpav\bootsafe>>autoexec. BAT appends content to an automatic batch file
C:>type AUTOEXEC. BAT displays the automatic batch file
@ECHO off
C:\CPAV\BOOTSAFE

(8) Print the output to the printer or print the control code
Format: ECHO Printer control Code >; PRN
ECHO Print Content >; PRN
The following example is the input print control code to the M-1724 printer. 156 is to press the ALT key to type 156 on the keypad, and so on:
C:>echo +156+42+116>; PRN (Input underline command fs*t)
C:>echo [email=+155@]+155@>; Prn[/email] (Input initialization command esc@)
c:>echo.>; PRN (line Wrap)

(9) Ringing the horn
C:>echo ^g
"^g" is a ctrl+g or alt+007 input in a DOS window, and entering multiple ^g can produce multiple beeps. The use method is to add it directly to a batch file or to make a batch file call.
Here the "^g" belong to the use of special symbols, see the chapters later in this article

3, PAUSE

PAUSE, the people who play the game know that the pause means
This is where you stop the execution of the system commands and display the following content.
Cases:
PAUSE
Run the display:
Please press any key to continue ...
To display additional prompts, you can do this by:
Echo Other Tips & Pause > nul

4, ERRORLEVEL

Program return code
Echo%errorlevel%
The command line format allows you to view the return code at the end of each command run
Used to determine if a previous command was executed successfully
The default value is 0, and General Command execution error will set ERRORLEVEL to 1

5. Title

Set the caption of the cmd window
Title New titles #可以看到cmd窗口的标题栏变了

6, COLOR

Sets the default console foreground and background color.
COLOR [attr]
ATTR Specifies the color properties of the console output
The color properties are specified by two hexadecimal digits-the first is the background and the second is
Prospect. Each number can be one of any of the following values:
0 = Black 8 = Gray
1 = Blue 9 = light Blue
2 = green A = Light Green
3 = Lake Blue B = Light Green
4 = Red C = Light Red
5 = Purple D = Lavender
6 = Yellow E = Light Yellow
7 = White F = Bright White
If no arguments are given, the command restores the color to CMD. EXE when started
The color. This value comes from the current console window,/T switch, or
DefaultColor registry value.
If you use the same foreground and background color to execute the color command, the color command
will set the ERRORLEVEL to 1.
For example: "COLOR FC" produces bright red on bright white

7, Mode configuration system equipment

Configure system devices.
Serial port: MODE comm[:] [baud=b] [parity=p] [Data=d] [stop=s]
[To=on|off] [Xon=on|off] [Odsr=on|off]
[Octs=on|off] [DTR=ON|OFF|HS]
[RTS=ON|OFF|HS|TG] [Idsr=on|off]
Device status: MODE [device] [/status]
Print redirection: MODE lptn[:]=comm[:]
Selected code page: MODE con[:] CP select=yyy
code page Status: MODE con[:] CP [/status]
Display mode: Mode con[:] [cols=c] [lines=n]
Keystroke rate: MODE con[:] [rate=r Delay=d]
Cases:
Mode con cols=113 lines=15 & Color 9f
This command sets the DOS window size: 15 rows, 113 columns

8, GOTO and:

Goto will point programming friends will know that this is the meaning of the jump.
In batch processing allows to ": XXX" to build a label, and then goto XXX jump to the label: XXX, and then execute the order after the label.
Cases:
if {%1}=={} goto noparms
If "%2" = = "" Goto noparms
The name of the tag can be random, but it is best to have a meaningful string, preceded by a colon to indicate that the string is a label, and the Goto command is based on this colon (:) to find the next jump to there. It's better to have some explanations so that you will be able to understand your intentions.

Cases:

@echo off
: Start
set/a var+=1
echo%var%
if%var% leq 3 GOTO start
pause

Run the display:
1
2
3
4

10. Start command

commands for calling external programs in batches (the external program runs in a new window, the batch program continues to execute, ignoring the health of the external program), and if the external program is run directly, it must wait for the external program to complete before continuing with the remaining instructions.
Example: Start Explorer D:\
Call the graphical interface to open the D disk

11, Assoc and Ftype

File association
Assoc Set ' File name extension ' Association, associated to ' file type '
Ftype set ' file Type ' association, associated with ' Execute program and Parameters '
When you double-click a. txt file, Windows is not directly judged by the. txt to open with Notepad.exe
It's the first to judge that. txt belongs to txtfile ' file type '
Then call the txtfile associated command line Txtfile=%systemroot%\system32\notepad. EXE%1
You can modify these 2 associations in Folder Options → file types
Assoc #显示所有 ' File name extension ' Association
Assoc. txt #显示. txt represents the ' file type ', and the results are shown. txt=txtfile
Assoc. Doc #显示. doc represents the ' file type ', and the results show. Doc=word.document.8
Assoc. exe #显示. exe represents the ' file type ' and the results are displayed. Exe=exefile
Ftype #显示所有 ' File Type ' association
Ftype Exefile #显示exefile类型关联的命令行, the result shows exefile= "%1"%*
Assoc. txt=word.document.8
Set. txt to a document of Word type, you can see that the icon for the. txt file has changed
Assoc. txt=txtfile
Restoring the correct association of. txt

Ftype exefile= "%1"%*
Restoring the correct association of Exefile
If the association has been corrupted, you can run Command.com, and then enter this command

12, pushd and POPD

Toggle current Directory
@echo off
C: & cd\ & MD MP3 #在 C:\ Create MP3 Folder
MD d:\mp4 #在 D:\ Create MP4 Folder
cd/d D:\mp4 #更改当前目录为 D:\mp4
pushd C:\mp3 #保存当前目录 and toggle the current directory to C:\mp3
POPD #恢复当前目录为刚才保存的 D:\mp4
It's generally not useful, and it helps when the current directory name is uncertain. (Useful in DOS programming)

13, call

The call command can invoke another batch during batch execution, and then continue with the original batch when another batch finishes executing

Call command

Calling a batch command, like executing a command effect directly, is useful in special cases, such as multilevel nesting of variables, as shown later in the tutorial. In batch programming, the command string can be generated according to certain conditions and can be executed using call, as shown in the example.

Call [Drive:][path]filename [Batch-parameters]

Other batch programs that are invoked. The filename parameter must have a. bat or. cmd extension.

Call:label arguments

Call the command segment within this file, which is equivalent to a subroutine. The called Command segment begins with a label: label
End with the command goto:eof.
In addition, the batch script text parameter references (% 0,% 1, and so on) have been changed as follows:
%* in the batch script indicate all parameters (such as%1%2%3%5 ...)
The substitution of batch parameters (%n) has been enhanced. You can use the following syntax: (see the example of a direct run that is not clear)
%~1-Remove quotation marks ("), extend%1
%~F1-Extend%1 to a fully qualified pathname
%~D1-Extend%1 to only one drive letter
%~P1-Extend%1 only to one path
%~N1-only extend%1 to a filename
%~X1-only extend%1 to a file extension
%~S1-extended path refers to a short name
%~A1-Extend%1 to file properties
%~T1-date/time when%1 was extended to a file
%~Z1-expands%1 to the size of the file
~ $PATH: 1-Find the directory listed in the PATH environment variable and add%1
Expands to the first fully qualified name found. If the environment
The variable name is not defined, or the file is not found, and this key combination
Extend to an empty string
You can combine modifiers to achieve multiple results:
%~DP1-Extend%1 only to drive letters and paths
%~NX1-Extend%1 only to file name and extension
%~dp$path:1-Find% 1 in the directory listed in the PATH environment variable,
and extend to the drive letter and path of the first file found.
%~FTZA1-expands%1 to an output line similar to DIR.
In the example above,%1 and PATH can be replaced by other valid values.
The ~ syntax is terminated by a valid parameter number. The ~ modifier cannot be used with%*
Note: When the parameter expands, regardless of whether the file represented by the parameter is real, it expands with the current directory
To understand the above knowledge, the following example is critical.
Cases:

@echo off
Echo generates a temporary file > Tmp.txt
Rem downlink First save the current directory, and then set C:\Windows to the current directory
pushd C:\Windows
call:sub Tmp.txt
Rem downlink Restore previous current directory
Popd
call:sub tmp.txt
pause
Del tmp.txt
exit
: Sub

Echo Delete Quote:%~1
Echo extended to Path:%~F1
Echo expands to a drive letter:%~D1
Echo extends to a path:%~P1
Echo extended to a filename:%~n1
Echo extends to a file name extension:%~x1
Echo extension path refers to contain short name:%~S1
Echo extended to file properties:%~A1
Echo extended to File date/time:%~T1
Echo expands to file size:%~z1
Echo extends to drive letter and path:%~DP1
Echo extends to file name and extension:%~nx1
Echo extends to output rows similar to DIR:%~FTZA1
Echo.

Goto:eof
Cases:

Set aa=123456
set Cmdstr=echo%aa% call
%cmdstr%
Pause

In this case, if call is not used, and the%cmdstr% is run directly, the result%aa%, instead of 123456, is displayed.

14, shift

Change the location of replaceable parameters in a batch file.
SHIFT [/n]
If the command extension is enabled, the SHIFT command supports the/n command-line switch, and the command line switch tells
The command shifts from the nth argument; n is between 0 and eight. For example:
Shift/2
Will shift%3 to%2, shift% 4 to%3, and so on, and will not affect%0 and%1.

15, IF

IF condition to judge the statement, the syntax format is as follows:
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
For more detailed analysis, see the following chapters.

(1) if [NOT] ERRORLEVEL number command
If errorlevel this sentence must be placed behind one of the commands, and the if errorlevel to determine the return value of the command after executing the command.
Number's numeric range is 0~255, and the order of the values should be from large to small. When the value returned is greater than or equal to the specified value, the condition is set to
Example:
@echo off
dir c:
The REM exit code jumps to Heading 1 for >=1 and >=0 jumps to heading 0 to perform the
IF errorlevel 1 goto 1
IF errorlevel 0 goto 0
The above two lines of Rem are not interchangeable, otherwise the failure also shows success.
: 0
The echo command was executed successfully!
Rem Program execution skip to title Exit
Goto Exit
: 1
Echo command failed!
Rem Program completion skip to title Exit
Goto Exit
: Exit
Pause
Run Display: Command execution successful!
(2) IF [not] string1==string2 command
string1 and string2 are characters, the uppercase and lowercase characters will be treated differently, and the equals number in this condition must be two (absolutely equal)
When the condition is equal, the following command
detects the value of the current variable and, in order to prevent the string from having spaces, can be
if [not] {string1}=={string2} command
If [NOT] [ STRING1]==[STRING2] Command
If [not] "string1" = "string2" command
This type of writing actually takes parentheses or quotes as part of a string, as long as the equals sign is aligned on both sides of the line, For example, the following writing is not possible:
If {string1}==[string2] command

(3) IF [NOT] EXIST filename command
EXIST filename is the meaning of the existence of a file or directory
echo off
IF EXIST autoexec.bat echo file exists!
IF not EXIST autoexec.bat echo file does not exist!
This batch of processing can be placed in C and D, respectively, to see the effect

16, setlocal and variable delay

This article refers to a batch tutorial of [Heroic Productions]:
In order to step, variable delay is a must pass! So this part wants you to look at it seriously.
To better illustrate the problem, let's first introduce an example.

Example 1:

@echo off
set a=4
set A=5 & echo%a%
pause

Results: 4

Explanation: Why 4 instead of 5? Did you change the value of variable A to 5 before echo?
Let's take a look at the mechanics of batch run commands:
When a batch reads a command, it is read by row (for example, for a for command, and so on, followed by all the statements closed with a pair of parentheses), to complete the necessary preprocessing before processing, which includes assigning values to variables in the row command. We now analyze example 1, batch processing before running to this sentence "set A=5 & Echo%a%", read this sentence whole sentence and do preprocessing--assign a value to variable A, then%a% of course is 4! (without why, batching does this.) )
In order to be able to perceive the dynamic change of environment variables, the batch process design the variable delay. In short, after reading a complete statement, you do not immediately assign a value to a variable of that row, and then you assign it before a single statement executes, which means "delay" the assignment to the variable.
So how do you open a variable delay? What do you need to notice about variable delay? For example, explain:

Example 2:

@echo off
setlocal enabledelayedexpansion
set a=4
set A=5 & Echo!a!
Pause 

Results: 5
Explanation: The variable delay is initiated and the correct answer is obtained. The start statement for variable delay is "setlocal enabledelayedexpansion" and the variable is "!!" with a pair of exclamation mark Enclosed (note the exclamation mark in English), otherwise there is no effect of variable delay.
To analyze Example 2, first "setlocal enabledelayedexpansion" to open the variable delay, and then "set a=4" first assigns a value of variable A to

4, "Set A=5 & Echo!a!" This sentence is to assign a value of variable A to 5 and output (because the variable delay is started, so the batch can perceive dynamic changes, that is, not first to the row variable assignment, but in the run process to assign a value to the variable, so at this time a value is 5).
Let me give you another example to solidify.
Example 3:

@echo off
setlocal enabledelayedexpansion
for/l%%i in (1,1,5) do (
set a=%%i
echo!a!
)
Pause

Results:
1
2
3
4
5

Explanation: This example opens the variable delay and uses the "!!" The variables are expanded so that we get the results we expect. What happens if the variable delay is not used
What's the result? The result is this:
ECHO is in a closed state.
ECHO is in a closed state.
ECHO is in a closed state.
ECHO is in a closed state.
ECHO is in a closed state.
That is, there is no sense of dynamic change in the For statement.
Tip: When a variable delay is not turned on, the variable in a command line must be changed to the next command. This can also be exploited to see examples.
Example: Swapping the values of two variables without intermediate variables

@echo off
:: Purpose: To swap the values of two variables, but not to use temporary variables
:: Code by JM 2007-1-24 [Email=cmd@xp]cmd@xp[/email]
:: Source: http:// www.cn-dos.net/forum/viewthread.php?tid=27078
set VAR1=ABC
set var2=123
echo Exchange before: var1=%var1% var2=% var2%
Set var1=%var2%& set var2=%var1%
echo Exchange: var1=%var1% var2=%var2% Pause

17, ATTRIB Display or change file properties

ATTRIB [+r|-r] [+a|-a] [+s|-s] [+h|-h] [[Drive:] [path] filename] [/S [/d]]
+ Set properties.
-Clears the properties.
R read-only file properties.
A Archive file attribute.
S System file properties.
H hidden file properties.
[Drive:] [Path] [FileName]
Specifies the file attributes to process.
/S handles matching files in the current folder and its subfolders.
/d also processes folders.

Cases:

MD Autorun
attrib +a +s +h autorun

The above command establishes the folder Autorun and then sets it to the archive, system, hidden properties

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.