In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Bat command introduction and advanced skills example analysis, for this problem, this article describes in detail the corresponding analysis and solutions, hoping to help more partners who want to solve this problem to find a more simple and easy way.
Basic batch processing Section 1 introduction to commonly used batch Internal commands
Batch definition: as the name implies, a batch file is a collection of commands in a certain order into an executable text file with the extension BAT or CMD. These commands are collectively referred to as batch commands.
Tip: you can press the Ctrl+C key combination on the keyboard to forcibly terminate the execution of a batch.
After understanding the general meaning, we officially began to study. First look at a simple example!
@ echo off
Echo "Welcome!"
Pause
Save the above three commands as a file test.bat or test.cmd and execute them
He will display the following two jargon on the screen:
Welcome to very!
Please press any key to continue. . .
This is a simple batch file, which uses a total of two commands\ "echo\" and\ "pause\" and a special symbol\ "@\"
From the above simple batch processing, we can find that batch processing is actually a combination of some symbols with special meaning and some commands that complete specified functions, so how many such special symbols and functional commands are there in batch processing? Let's take a closer look at some of the most commonly used ones now!
(the following content comes from the network, please read it carefully so that you can get to the example in the next section)
Common commands for batch processing (there are still many commands not enumerated, please check the help information)
1. REM and:
2, ECHO and @
3 、 PAUSE
4 、 ERRORLEVEL
5 、 TITLE
6 、 COLOR
7. Mode configures system devices
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 displays or changes file properties
Introduction command
1. REM and:
REM is a comment command, which is generally used to annotate the program. The content after the command is not executed, but can be echoed.
Second,:: can also play the role of rem annotation, and more concise and effective, but there are two points to note:
First, any character line that begins with a colon is treated as a label in the batch and everything that follows is directly ignored.
Valid label: the colon is followed by an alphanumeric string that can be recognized by the goto statement.
Invalid label: the colon is followed by a special symbol that is not alphanumeric, and the label that goto cannot recognize can play the role of annotation, so:: is often used as an annotation symbol, in fact: + can also play the role of annotation.
Second, unlike rem, the character line after:: will not be echoed when executed, regardless of whether you open the command line echo state with echo on or not, because the command interpreter does not think it is a valid command line, from this point of view, rem will be more applicable than:: in some cases; in addition, rem can be used in config.sys files.
Inline comment format:% comment content% (not commonly used, use with caution)
2, ECHO and @
Placing the @ character in front of a command turns off the echo of the command, regardless of whether the echo is open or not.
The functions of the echo command are listed as follows:
(1) turn echo on or off
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 status
Format: echo
(3) output prompt information
Format: ECHO message content
These are the three common uses of the ECHO command, which you are familiar with and can use, but as a gold digger of the DOS command, you should also know the following techniques:
(4) close the DOS command prompt
By typing ECHO OFF at the DOS prompt, you can turn off the display of the DOS prompt so that only the cursor is left on the screen until you type ECHO ON before the prompt reappears.
(5) output a blank line, which is equivalent to entering an enter
Format: ECHO.
It is worth noting that the "." on the command line should be followed by ECHO without a space, otherwise "." will be output to the screen as a prompt. In addition, "." can be replaced with any symbol such as,:; / [\] +.
The return of the command ECHO. Output can be turned through the DOS pipeline as input to other commands, such as echo. | time is equivalent to giving a carriage return after the execution of the TIME command. So when executing, the system will automatically return to the DOS prompt after the current time is displayed.
(6) reply to questions in the order
Format: ECHO reply | Command file name
The above format can be used to simplify the operation of some commands that require man-machine dialogue (such as: CHKDSK/F;FORMAT Drive:;del *.). It uses the preset response language output of the ECHO command as the input of the man-machine dialogue command through the DOS pipeline command. The following example is equivalent to entering "Y" enter when a man-machine conversation occurs in the invoked command:
C: > ECHO Y | CHKDSK/F
C: > ECHO Y | DEL A: *. *
(7) create new documents or add document contents.
Format: ECHO file content > file name
ECHO file contents > > file name
For example:
C: > ECHO @ ECHO OFF > AUTOEXEC.BAT sets up automatic batch files
C: > ECHO C:\\ CPAV\\ BOOTSAFE > > AUTOEXEC.BAT appends content to the automatic batch file
C: > TYPE AUTOEXEC.BAT displays the automatic batch file
@ ECHO OFF
C:\\ CPAV\\ BOOTSAFE
(8) output the printed content or print control code to the printer
Format: ECHO printer control code > RN
ECHO print content > RN
The following example is to input a print control code to the MMel 1724 printer. < Alt > 156 is to hold down the alt key and type 156 on the keypad, and so on:
C: > ECHO + 156 / 42 / 116 > RN (enter the underscore command FS*t)
C: > ECHO [email=+155@] + 155 @ > RN [/ email] (enter the initialization command ESC@)
C: > ECHO. > RN (newline)
(9) make the horn sound
C: > ECHO ^ G
"^ G" is entered with Ctrl+G or Alt+007 in the dos window. Entering multiple ^ G can produce multiple tones. The way to use it is to add it directly to the batch file or make it into a batch file call.
The "^ G" here belongs to the use of special symbols. Please see the later chapter of this article.
3 、 PAUSE
PAUSE, everyone who plays the game knows the meaning of time-out.
In this case, stop the execution of the system command and display the following.
Example:
PAUSE
The run shows:
Please press any key to continue. . .
To display other prompts, you can use:
Echo other prompts pause > nul
4 、 errorlevel
Program return code
Echo errorlevel%
At the end of each command run, you can view the return code in this command line format
Used to judge whether the command just was executed successfully
The default value is 0. If an error occurs in the execution of a command, errorlevel is set to 1.
5 、 title
Set the title of the cmd window
Title new title # you can see that the title bar of the cmd window has changed
6 、 COLOR
Sets the default console foreground and background colors.
COLOR [attr]
Attr specifies the color attribute of the console output
The color property is specified by two hexadecimal digits-the first is the background and the second is
Foreground. Each number can be one 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 = * E = light * *
7 = White F = bright white
If no parameters are given, the command restores the color to when CMD.EXE starts
It's the color. This value comes from the current console window, / T switch, or
DefaultColor registry value.
If you execute the COLOR command with the same foreground and background color, the COLOR command
ERRORLEVEL is set to 1.
For example:\ "COLOR fc\" produces bright red on bright white.
7. Mode configures system devices
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]
Example:
Mode con cols=113 lines=15 color 9f
This command sets the DOS window size: 15 rows, 113 columns
8. GOTO and:
GOTO's friends who know how to program will know that this means jump.
It is allowed to build a label with ": XXX" in the batch, then use GOTO XXX to jump to the label: XXX, and then execute the labeled command.
Example:
If {% 1} = = {} goto noparms
If\ "% 2\" = =\ "\" goto noparms
The name of the tag can be chosen at will, but it is better to be a meaningful string, preceded by a colon to indicate that the string is a tag, and the goto command is based on this colon (:) to find the next step to jump there. You'd better have some instructions so that you and others will seem to understand your intentions.
Example:
@ echo off:startset / a var+=1echo var%if var% leq 3 GOTO startpause
The run shows:
one
two
three
four
9 、 find
Search for strings in the file.
FIND [/ V] [/ C] [/ N] [/ offline [line]\ "string\" [[drive:] [path] filename [...]]
/ V displays all lines that do not contain the specified string.
/ C displays only the number of lines that contain a string.
/ N displays the line number.
/ I ignores case when searching for strings.
/ OFF [LINE] do not skip files with offline property sets.
\ "string\" specifies the text string to search for
[drive:] [path] filename
Specify the files to search for.
If no path is specified, FIND searches for text typed or generated by another command.
Find is often used in conjunction with the type command
Type [drive:] [path] filename | find\ "string\" [> tmpfile] # pick the line containing string
Type [drive:] [path] filename | find / v\ "string\" # remove lines containing string in the file
Type [drive:] [path] filename | find / c # shows the number of file lines
The above usage removes the prompt (file name prompt) that comes with the find command.
Example:
@ echo offecho 111 > test.txtecho 22 2 > test.txtfind\ "111\" test.txtdel test.txtpause
The run is shown as follows:
-TEST.TXT
one hundred and eleven
Please press any key to continue. . .
Example:
@ echo offecho 111 > test.txtecho 22 2 > test.txttype test.txt | find\ "111\" del test.txtpause
The run is shown as follows:
one hundred and eleven
Please press any key to continue. . .
10. Start command
A command that invokes an external program in a batch (the external program runs in a new window, and the batch program continues to execute, regardless of the running status of the external program). If you run the external program directly, you must wait for the external program to complete before continuing to execute the remaining instructions
Example: start explorer d:\\
Call the graphical interface to open the D disk
11, assoc and ftype
File association
Assoc setting # 39; file extension 'association, associated to' file type'
Ftype setting # 39; file type 'association, associated to' executor and parameters'
When you double-click a .txt file, windows does not open it with notepad.exe based on the .txt direct judgment.
Instead, it is judged that .txt belongs to txtfile # 39; file type'
Then call the command line associated with txtfile txtfile=%SystemRoot%\\ system32\\ NOTEPAD.EXE% 1
You can modify these two associations in\ "folder options\" →\ "File types\"
Assoc # shows all # 39; file extension 'associations
Assoc .txt # shows the # 39; file type represented by .txt, and the result shows .txt = txtfile
Assoc .doc # shows the # 39; file type represented by .doc, and the result shows .doc = Word.Document.8
Assoc .exe # shows the # 39; file type represented by .exe, and the result shows .exe = exefile
Ftype # shows all # 39; file type 'associations
Ftype exefile # displays the command line associated with the exefile type, which shows exefile=\ "% 1\"% *
Assoc .txt = Word.Document.8
If you set .txt to a document of type word, you can see that the icons of the .txt file have changed.
Assoc .txt = txtfile
Restore the correct association of .txt
Ftype exefile=\ "% 1\"% *
Restore the correct association of exefile
If the association has been broken, you can run command.com and enter this command
12. Pushd and popd
Toggle current directory
@ echo offc: cd\\ & md mp3# create mp3 folder md d:\\ mp4# in D:\\ create mp4 folder cd / d:\\ mp4# change the current directory to d:\ mp4pushd c:\\ mp3# save the current directory and change the current directory to c:\ mp3popd# restore the current directory to the d:\\ mp4 you just saved
It is generally not very useful, and it will be helpful 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 to execute the original batch after the other batch has been executed.
CALL command
Invoking a batch command has the same effect as executing the command directly, which is useful in special cases, such as multi-level nesting of variables, as shown later in the tutorial. In batch programming, you can generate a command string according to certain conditions, which can be executed with call, as shown in the example.
CALL [drive:] [path] filename [batch-parameters]
Other batch programs called. The filename parameter must have a .bat or .cmd extension.
CALL: label arguments
Call the command section in this file, which is equivalent to a subroutine. The called command segment begins with the label: label
Ends with the command goto: eof.
In addition, the parameters of the script (% 0,% 1, etc.) have been changed as follows:
The% * in the batch script indicates all parameters (such as% 1% 2% 3% 4% 5.)
The substitution of the batch parameter (% n) has been enhanced. You can use the following syntax: (run the following example directly if you don't understand)
% ~ 1-Delete quotation marks (\ "), expand% 1
% ~ F1-extends% 1 to a fully qualified pathname
% ~ D1-expand% 1 to only one drive letter
% ~ p1-extend% 1 to only one path
% ~ N1-expand% 1 to only one file name
% ~ x1-extend% 1 to only one file extension
The path of% ~ S1-extension contains a short name
% ~ A1-extends% 1 to file attributes
% ~ T1-extend% 1 to the date / time of the file
% ~ Z1-expand% 1 to the size of the file
% ~ $PATH: 1-find the directory listed in the PATH environment variable and set% 1
Expand to the first fully qualified name found. If the environment
If the variable name is not defined, or the file is not found, this key combination will
Expand to an empty string
You can combine modifiers to achieve multiple results:
% ~ dp1-extends% 1 only to the drive letter and path
% ~ nx1-extends% 1 only to the file name and extension
% ~ dp$PATH:1-look for% 1 in the directory listed in the PATH environment variable
And expand to the drive letter and path of the first file found.
% ~ ftza1-extends% 1 to output lines like DIR.
In the above example,% 1 and PATH can be replaced by other valid values.
% ~ the syntax is terminated by a valid parameter number. % ~ modifier cannot be used with% *
Note: when expanding the parameter, regardless of whether the file represented by the parameter exists or not, it is expanded with the current directory.
To understand the above knowledge, the following example is crucial.
Example:
@ echo offEcho generates a temporary file > tmp.txtRem the following line to save the current directory first Then set c:\\ windows to the current directory pushd c:\\ windowsCall: sub tmp.txtRem downlink to restore the previous current directory PopdCall: sub tmp.txtpauseDel tmp.txtexit:subEcho delete quotation marks:% ~ 1Echo extension to path:% ~ f1Echo extension to a drive letter:% ~ d1Echo extension to a path:% ~ p1Echo extension to a file name:% ~ n1Echo extension to a file extension:% ~ x1Echo extension Short name:% ~ s1Echo extension to file attribute:% ~ date / time of a1Echo extension to file:% ~ t1Echo extension to file size:% ~ z1Echo extension to drive letter and path:% ~ dp1Echo extension to file name and extension:% ~ nx1Echo extension to DIR-like output line:% ~ ftza1Echo.Goto: eof
Example:
Set aa=123456
Set cmdstr=echo aa%
Call cmdstr%
Pause
In this example, running% cmdstr%, instead of call will show the result% aa%, instead of 123456
14 、 shift
Change the location of replaceable parameters in the batch file.
SHIFT [/ n]
If the command extension is enabled, the SHIFT command supports the / n command line switch, which tells the
The command shifts from the nth argument; n is between zero and eight. For example:
SHIFT / 2
Will shift 3 to 2, 4 to 3, and so on; and will not affect 0 and 1.
15 、 IF
The syntax format of IF conditional judgment statement is as follows:
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
The following is described one by one. For a more detailed analysis, please see the following chapters.
(1) IF [NOT] ERRORLEVEL number command
The sentence IF ERRORLEVEL must be placed after a command, and it is up to IF ERRORLEVEL to determine the return value of the command after the command is executed.
The numerical value range of Number is 0255. it is judged that the order of values should be from large to small. The condition holds when the returned value is greater than or equal to the specified value.
Example:
If the @ echo offdir c:rem exit code is > = 1, jump to the title 1 and execute the two lines above the IF ERRORLEVEL 1 goto 1IF ERRORLEVEL 0 goto 0Rem if the exit code > = 0 is executed. Otherwise, failure will show success. The 0echo command was executed successfully! After the execution of the Rem program, jump to the title exit to exit the goto exit:1echo command execution failed! After the execution of the Rem program, skip to the title exit and exit goto exit:exitpause.
The operation shows that the command was executed successfully!
(2) IF [NOT] string1==string2 command
String1 and string2 are both character data. The case of characters in English will be regarded as different. In this condition, the equal sign must be two (absolutely equal).
When the conditions are equal, the subsequent command is executed.
To detect the value of the current variable to make a decision, to prevent spaces in the string, you can use the following format
If [NOT] {string1} = = {string2} command
If [NOT] [string1] = = [string2] command
If [NOT]\ "string1\" =\ "string2\" command
This way of writing actually treats parentheses or quotation marks as part of a string, as long as the left and right sides of the equal sign are consistent, such as the following:
If {string1} = = [string2] command
(3) IF [NOT] EXIST filename command
EXIST filename means 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!
You can execute this batch on disk C and disk D respectively to see the effect.
16. Setlocal and variable delay
The content of this article refers to the batch processing tutorial produced by Hero:
If you want to advance, variable delay is a must! So I hope you can take a closer look at this part.
In order to better illustrate the problem, let's introduce an example first.
Example 1:
@ echo offset a=4set axi5 echo% a%pause
Results: 4
Explanation: why 4 instead of 5? Have you changed the value of variable a to 5 before echo?
Let's first take a look at the mechanism for batch running commands:
When a batch reads a command, it is read by line (for example, the for command, etc., and all statements closed with a pair of parentheses are treated as one line), and the necessary preprocessing work is completed before processing, including the assignment of variables in the line command. Let's now analyze example 1, the batch reads and preprocesses the whole sentence before running to the sentence "set axi5 echo% a%"-- if you assign a value to the variable a, then the% a% is of course 4! (for no reason, that's what batch processing does. )
In order to perceive the dynamic changes of environmental variables, the variable delay is designed for batch processing. To put it simply, after reading a complete statement, the variable of the row is not assigned immediately, but before a single statement is executed, that is, the assignment of the variable is "delayed".
So how do you turn on variable delay? What do you need to pay attention to about variable delay? Give an example to illustrate:
Example 2:
@ echo offsetlocal enabledelayedexpansionset a=4set axi5 echo! axipause
Results: 5
Explanation: variable delay is started and the correct answer is obtained. The delayed startup statement for the variable is "setlocal enabledelayedexpansion", and the variable uses a pair of exclamation marks "!!" Wrap it up (pay attention to the English exclamation mark), otherwise there will be no effect of variable delay.
To analyze example 2, first "setlocal enabledelayedexpansion" turns on the variable delay, and then "set axiom 4" first assigns the variable a to
4, "set axiom 5 echo! a!" This sentence assigns the variable a to 5 and outputs (because of the delay in starting the variable, the batch can sense the dynamic change, that is, it does not assign a value to the variable first, but to the variable during operation, so the value of an is 5).
Give me another example to consolidate it.
Example 3:
@ echo offsetlocal enabledelayedexpansionfor / l% I in (1penny 1je 5) do (set a=%%iecho! a!) pause
Results:
one
two
three
four
five
Explanation: this example turns on variable delay and uses "!!" Expand the variables so that we get the expected results. What happens if you don't use variables to delay?
What's the result? The result is this:
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
That is, you are not aware of the dynamic changes in the for statement.
Tip: in the case of no delay in opening variables, variable changes in a command line must not be reflected until the next command. This point can also be taken advantage of. Look at the example.
Example: exchange the values of two variables without intermediate variables
@ echo off:: purpose: exchange the values of two variables, but do not use temporary variables:: Code by JM 2007-1-24 [email=CMD@XP] CMD@ XP [/ email]:: provenance: http://www.cn-dos.net/forum/viewthread.php?tid=27078set var1=abcset var2=123echo before exchange: after var1=%var1% var2=%var2%set var1=%var2% set var2=%var1%echo exchange: var1=%var1% var2=%var2%pause17, ATTRIB display or change file properties
ATTRIB [+ R |-R] [+ A |-A] [+ S |-S] [+ H |-H] [[drive:] [path] filename] [/ S [/ D]]
+ set properties.
-clear the attribute.
R read-only file properties.
An Archive file properties.
S system file properties.
H hides file properties.
[drive:] [path] [filename]
Specifies the file properties to be processed.
/ S processes matching files in the current folder and its subfolders.
/ D also handles folders.
Example:
Md autorun
Attrib + a + s + h autorun
The above command creates the folder autorun, and then sets it as archive, system, hidden properties
Section 2 Special symbols commonly used
1. @ command line echo mask
2.% batch variable leader
3. > redirector
4, > > redirector
5. Redirector
Output redirect command
This character means to pass and overwrite, and its role is to pass the result of the run to the following scope (either a file or the default system console).
In the NT series of command lines, the scope of redirection changes from the entire command line to a single command statement, restricted by the command delimiter, & &, |, and statement blocks.
For example:
Use the command: echo hello > 1.txt to create the file 1.txt with the content "hello" (notice a space at the end of the line)
Use the command: echo hello > 1.txt to create the file 1.txt with the content "hello" (note that there is no space at the end of the line)
4, > > redirector
Output redirect command
The function of this symbol is somewhat similar to >, but the difference is that > > is passed and appended at the end of the file, while > is overridden.
Usage is the same as above
Also take 1.txt as an example.
Use the command:
Echo hello > 1.txt
Echo world > > 1.txt
At this point, the 1.txt content is as follows:
Hello
World
5. Nul forbids the output of correct information
2 > nul means that the output of error messages is prohibited.
Where 1 and 2 are addresses that represent the input and output of a data stream (NT CMD calls it a handle and MSDOS calls it a device).
Handle 0: standard input stdin, keyboard input
Handle 1: standard output stdout, output to the command prompt window (console, code CON)
Handle 2: standard error stderr, output to the command prompt window (console, code CON)
The stdin can be redirected by >.
We already know that you can use the for command to read the contents of the text, but it's a bit troublesome to use the for command if you only need to read the first line. The simple solution is as follows:
@ echo offset / p str=1.txt
The result is: test > 1.txt
He didn't add it to 1.txt, hehe. It just shows it.
In addition, this escape character can also be used as a continuation symbol.
Take a simple example:
@ echo offecho hero ^ is ^ good ^ man pause
Needless to say, you'll see if you try it yourself.
Why does an escape character act as a continuation character at the end of a line? The reason is simple, because there is an invisible symbol at the end of each line, the carriage return, which is invalidated when the escape character is at the end of the line, thus continuing the line.
8. Combine commands
Syntax: the first command, the second command [& the third command.]
, & &, | | is a combined command, which, as the name implies, can be executed by combining multiple commands into a single command. This is allowed in batch scripts and is widely used. Because the batch process does not recognize the number of commands.
This symbol allows you to use more than two different commands on one line, and when the first command fails, it does not affect the execution of subsequent commands.
The commands on both sides are executed sequentially, from the back to the back.
For example:
Dir z:\\ dir y:\ & dir c:\\
The above command will continuously display the contents of disk zMY and c, regardless of whether the disk exists.
9. & combination command
Syntax: the first command & the second command [& & the third command.]
In this way, multiple commands can be executed at the same time. When there is an error in the execution of the command, the subsequent command will not be executed, and all the commands will be executed all the time if there has been no error.
This command is similar to the one above, but the difference is that when the first command fails, the later command will not be executed
Dir z:\ & dir y:\ & & dir c:\\
10. | | combine commands
Syntax: first command | | second command [| | third command.]
In this way, multiple commands can be executed at the same time. When one command fails, the second command is executed. When the correct command is executed, the subsequent command will not be executed. If there is no correct command, all the commands will be executed all the time.
Tip: priority must be paid to when using the combined command with the redirect command.
Pipe commands take precedence over redirect commands, and redirect commands take precedence over combined commands.
Problem: list the files and folders of disk C and disk D in the a.txt file. Look at the example:
Dir c:\\ & dir d:\ > a.txt
After this execution, there is only D disk information in the a.txt! Why? Because the priority of the combined command is not as high as that of the redirect command! So this sentence divides the line into two parts when executed: dir c:\\ and dir d:\\ > a.txt, not as you might think: dir c:\ & dir d:\\ and > a.txt. To use the combined command & & to meet the requirements of the title, you must write:
Dir c:\\ > a.txt & dir d:\\ > a.txt
In this way, according to the priority, DOS will divide the sentence into the following two parts: dir c:\ > a.txt and dir d:\ > a.txt. The difference of a few sentences in example 18 is quite special and is worth studying and understanding.
Of course, you can also use commands here (think for yourself):
Dir c:\ > a.txt dir d:\ > a.txt
11.\ "\" string delimiter
Double quotation marks allow you to include spaces in a string, and you can enter a special directory in the following ways
Cd\ "program files\"
Cd progra~1
Cd pro*
The above three methods can be entered into the program files directory
12. Comma
Commas are equivalent to spaces, and in some cases "," can be used as spaces to make
such as
Dir,c:\\
13; semicolon
Semicolon, when the command is the same, different targets can be used to isolate, but the execution effect remains the same. If an error occurs during execution, only an error report is returned, but the program will still execute. (some people say that they will not continue to execute, but in fact, you will know after a test.)
For example:
Dir c:\\; d:\\; e:\\; z:\\
The above command is equivalent to
Dir c:\\
Dir d:\\
Dir e:\\
Dir f:\\
If the z disk does not exist, the run shows that the system cannot find the specified path. Then terminate the execution of the command.
Example: dir c:\\; d:\\; e:\\ 1.txt
The above command is equivalent to
Dir c:\\
Dir d:\\
Dir e:\\ 1.txt
The file e:\\ 1.txt does not exist, but the e disk exists and there is an error prompt, but the command will still be executed.
Why? If the destination path does not exist, execution is terminated; if the path exists and only the file does not exist, execution continues.
14. () brackets
Parentheses play a special role in batch programming, the left and right parentheses must be used in pairs, and the parentheses can include multiple lines of commands, which are treated as a whole and as a command line.
Parentheses are common in for and if statements and are used to nest loops or conditional statements. In fact, parentheses () can also be used alone, as shown in the example.
Example:
Command: echo 1 echo 2 & echo 3
It can be written as:
(
Echo 1
Echo 2
Echo 3
)
The effect of the above two ways of writing is the same, both of which are considered to be a command line.
Note: when such multiple commands are treated as one command line, variable latency is involved if there are variables in it.
15 、! Exclamation point
There is nothing to say, in the case of variable delay, it is used to represent variables, that is,% var% should be expressed as! varials, see the previous introduction to the setlocal command.
Chapter 2 DOS loop: detailed explanation of the for command
Before we talk about FOR, let me tell your novice friends that if you have any commands that you don't understand, enter them directly under CMD:
Name /? In this format, the help files given by the system, such as for /? It will show all the help of the FOR command! Of course, many rookies don't understand. That's why there are so many batch articles! I also take care of the rookie and explain the FOR command in my own way!
Officially begin:
I. basic format
FOR% variable IN (set) DO command [command-parameters]
% variable specifies a single letter to represent a replaceable parameter.
(set) specify a file or group of files. You can use wildcards.
Command specifies the commands to be executed on each file.
Command-parameters
Specify parameters or command line switches for a specific command.
Parameters: FOR has 4 parameters / d / l / r / f their role I will explain with examples below
Now let's talk about the meaning of each parameter.
Second, parameter / d
FOR / D% variable IN (set) DO command [command-parameters]
If the set contains wildcards, specify to match the directory name, not the file
The first name matches.
If the Set (that is, the\ "related file or command\" I wrote above) contains wildcards (* and?), the specified Command will be executed for each directory that matches the Set (instead of the filegroup in the specified directory).
This parameter is mainly used for directory search, but not for files. Take a look at this example.
@ echo off
For / d% I in (c:\\ *) do echo% I
Pause
The run will print out all the directory names under the root directory of the C disk, and none of the file names will be displayed!
Another one, for example, we need to type out the name of the folder under the current path with only 1-3 letters.
@ echo off
For / d% I in Do echo I
Pause
In this way, if you have a directory name with only 1-3 letters in the current directory, it will be displayed, but if not, it will not be displayed.
Can you explain the * and? The role of the number, the * sign represents any N characters, and? The number represents only any character.
Know the effect, give everyone a question to think about!
@ echo off
For / d% I in (window?) Do echo I
Pause
If you save it to disk C, what will be displayed? See for yourself! Display: windows
The / D parameter can only display the name of the directory under the current directory, which we should pay attention to!
3. Parameter / R
FOR / R [[drive:] path]% variable IN (set) DO command [command-parameters]
Check the directory tree rooted in [drive:] path and point to the
FOR statement. If no directory is specified after / R, the current
Catalogue. If the set is only a single point (.) Character, the directory tree is enumerated.
Recursion
As we know above, / D can only display the directory name under the current path, so now this / R is also related to the directory, what can he do? Don't worry, he is much more powerful than / D.
It can read all the file names under the current or your specified path, note that it is the file name, what is the use to see the example!
Please note 2 points:
1. If the file name in set contains a wildcard character (? Or *), enumerate all files that match set in the directory specified by the / R parameter and its subdirectories below, and directories without matching files are not enumerated.
2. On the contrary, if the set is a specific file name and does not contain wildcards, enumerate the directory tree (that is, enumerate the directory and all the subdirectories below it), regardless of whether the specified file in set exists or not. This is the same as the single point (.) enumerated directory tree mentioned earlier, which represents the current directory and can also be regarded as a file.
Example:
@ echo off
For / r c:\% I in (* .exe) do echo% I
Pause
Let's save this BAT to D disk anywhere and execute it, and I will see that he lists all the EXE files under the root directory of C disk and the subdirectory of each directory!
Example:
@ echo off
For / r% I in (* .exe) do @ echo% I
Pause
The parameters are different! This command is not preceded by the C:\\, that is, the search path, so that he will use the current directory as the search path, such as your BAT. If you put him under the d:\\ test directory to execute, then he will list all the EXE files in the D:\\ test directory and his subdirectories!
Example:
@ echo off
For / r c:\% I in (boot.ini) do echo% I
Pause
Run this example and find that all directories on disk c are enumerated. In order to enumerate only the directories where boot.ini exists, it can be changed to the following:
@ echo off
For / r c:\% I in (boot.ini) do if exist% I echo% I
Pause
It's nice to search for files with this command.
This parameter should be understood! It's still a funny order!
4. Parameters / L
FOR / L% variable IN (start,step,end) DO command [command-parameters]
This set represents a sequence of numbers from beginning to end in increments.
Therefore, the sequence 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 5, 1, 4, 4, 4, 4, 5, 5, 4, 4, 4, 5, 5, 4, 4, 4, 5, 5, 4, 4, 4, 5, 1, 4,
Sequence (5-4-3-21).
Use the iteration variable to set the start value (Start#), and then step through a range of values until the value exceeds the set end value (End#). / L will execute iterative variables by comparing Start# with End#. This command is executed if Start# is less than End#,. If the iteration variable exceeds End#, the command interpreter exits the loop. You can also use a negative Step# to incrementally execute values in this range. For example, (1) generate sequences 1 2 3 4 5), and (5) generate sequences (5 4 3 2 1). The syntax is:
Look at this means a little dizzy! Let's look at the example and we won't get dizzy!
@ echo off
For / l% I in (1meme 1meme 5) do @ echo% I
Pause
Save the execution to see the effect, he will print 5 numbers from 1 2 3 4 5
This parameter means to add 1 at a time from 1 to 5!
When you get dizzy, it's useful to print a number. Okay, to satisfy everyone, take a look at this example.
@ echo off
For / l% I in (1mem1mem5) do start cmd
Pause
After the implementation is not startled, why more than 5 CMD windows, ha ha! What will happen if you change that from (1pm) to (1pm) 65535? I will tell you first that 65535 CMD windows will be opened. You are strong if you don't die!
Of course, we can also change that start cmd to md% I so that we can set up a specified directory! The name is 1-65535.
After looking at this parameter that I have given the nature of destruction, let's look at the last parameter.
5. Parameters / F
\\ iteration and file parsing
Use file parsing to process command output, strings, and file contents. Use iterative variables to define the content or string to check, and use various options options to further modify the parsing. Use the options token option to specify which tokens should be passed as iteration variables. Note that when there is no token option, / F will only check the first token.
The file parsing process involves reading the output, string, or file contents, dividing it into separate lines of text, and parsing each line into zero or more tokens. The for loop is then called by setting the value of the iteration variable to the token. By default, / F passes the first white space delimiter on each line of each file. Skip blank lines.
The detailed help format is:
FOR / F [\ "options\"]% variable IN (file-set) DO command [command-parameters]
FOR / F [\ "options\"]% variable IN (\ "string\") DO command [command-parameters]
FOR / F [\ "options\"]% variable IN (# 39 command') DO command [command-parameters]
The quoted string\ "options\" includes one or more
Specify keywords for different parsing options. These keywords are:
Eol=c-refers to the end of a line comment character (just one)
Skip=n- refers to the number of lines ignored at the beginning of the file.
Delims=xxx- refers to the delimiter set. This replaces spaces and tabs
Default delimiter set.
Tokens=x,y,m-n- refers to which symbol of each line is passed to each iteration
The for itself. This results in the allocation of additional variable names. Mmurn
The format is a range. Specify the mth through the nth symbol. If
The last character in a symbol string, an asterisk.
Then the additional variables will be parsed after the last symbol
Assign and accept reserved text for lines. After testing, this parameter is the most.
Only 31 fields can be distinguished.
Usebackq- uses quotation marks (the key to the left of the number 1 on the keyboard).
When the parameter usebackq is not used: file-set represents a file, but cannot contain spaces
Double quotation marks indicate a string, that is,\ "string\"
Single quotation marks indicate the execution of a command, that is, # 39 command
When using the parameter usebackq: file-set and\ "file-set\" both represent files
When there is a space in the file path or name, it can be enclosed in double quotation marks
Single quotation marks indicate a string, that is, # 39
Quotation marks indicate the execution of the command, that is, `command`
The above is using for /? The help information obtained by the command is copied directly.
I'm dizzy! Let me give you an example to help you understand these parameters!
For command example 1:
@ echo offrem first set up a temporary file test.txtecho; comment line, this is a temporary file, delete > test.txtecho 11, 12, 13, 14, 15, 16 > > test.txtecho 21, 22, 23, 24, 25, 26 > > test.txtecho 31-32-33-34-35-36 > > test.txtFOR / F\ "eol=; tokens=1,3* delims=,-\"% I in (test.txt) do echo% I% j% kPauseDel test.txt%
Run to display the results:
11, 13, 14, 15, 16.
21, 23, 24, 25, 26.
31 paragraph 33 paragraph 34-35-36 paragraph
Please press any key to continue. . .
Why is this? Let me explain:
Behavior comment lines at the beginning of eol=; semicolon
Tokens=1,3* assigns paragraph 1, paragraph 3 and the remaining fields of each line to the variable%% iPerry% jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjmel% k, respectively.
Delims=,- (a space after a minus sign) is separated by a comma minus sign and a space, and the space must be placed last.
For command example 2:
@ echo offFOR / F\ "eol= delims=\"% I in (test.txt) do echo% iPause
The run will display the full contents of the test.txt, including comment lines, without explanation.
For command example 3:
In addition, the / F parameter can also see this example with the result of the output command.
@ echo offFOR / F\ "delims=\"% I in (# 39 world net user') do @ echo% ipause
In this way, all the account names of your machine will come out and enclose the contents of the extension in two single quotation marks to indicate that when the command is executed, FOR will return the result of each line of the command. Add that\ "delims=\" so that the line of my space can be displayed in the whole line, and only the left column of the space will be displayed if you don't add it!
Basically finished with the basic usage of FOR. If you look at FOR's system help, you will find that there are some specially defined variables below, which I will not talk about. Everyone should be tired! You're not tired. I'm tired.
Chapter III variables in the FOR command
There are some variables in the FOR command, and their usage is not well understood by many novice friends. I will explain their usage to you today!
First, list all the variables in FOR:
~ I-remove any quotation marks (\ ") and extend% I
% ~ fI- extends% I to a fully qualified pathname
% ~ dI- extends% I to only one drive letter
% ~ pI- extends% I to only one path
% ~ nI- extends% I to only one file name
% ~ xI- extends% I to only one file extension
The path to the% ~ sI- extension contains only short names
% ~ aI- extends% I to the file properties of the file
% ~ tI- extends% I to the date / time of the file
% ~ zI- extends% I to the size of the file
% ~ $PATH:I-find the directory listed in the path environment variable and extend% I
To the first fully qualified name found. If the environment variable name
If the file is not defined or the file is not found, this key combination will be extended to
Empty string
We can see that each line has an uppercase letter\ "I\". This I is actually the variable we brought in in FOR. We will write here what the variable name is in our FOR statement.
For example: FOR / F%% z IN (# 39% set') DO @ echo% z
The name of the variable we substituted here is z, then we have to change that I to z, for example,% ~ fI to% ~ fz
As for the previous% ~ p, this kind of content is grammar!
Okay, let's start with:
1. ~ I-remove any quotation marks (\ ") and extend% I
The function of this variable is just as he explained, delete the quotation marks!
Let's look at this example:
First, set up a temporary file temp.txt, which is as follows
\ "1111
\ "2222\"
3333\ "
"4444\" 44
\ "55\" 55
You can create a BAT file with the following code:
@ echo off
Echo ^\ "1111 > temp.txt
Echo\ "2222\" > temp.txt
Echo 3333 ^\ "> > temp.txt
Echo\ "4444\" 44 > > temp.txt
Echo ^\ "55\" 55 > > temp.txt
Set up temporary files on rem. Note that unpaired quotation marks should be accompanied by escape characters ^. Do not leave spaces before redirecting symbols.
FOR / F\ "delims=\"% I IN (temp.txt) DO echo%%~i
Pause
Del temp.txt
After execution, we see the echo of CMD as follows:
The quotation marks before the 1111 # string have been deleted
The quotation marks at the beginning and end of the 2222 # string have been deleted.
There are no quotation marks before the 3333\ "# string and the quotation marks are reserved after the string.
The quotation marks before the 4444\ "4" string are deleted, while the quotation marks in the middle are retained.
The quotation marks before the 55\ "55\" 55 # string are deleted, while the quotation marks in the middle are retained
Please press any key to continue. . .
Compared with the previous temp.txt, we will find that the quotation marks on lines 1, 2, and 5 have disappeared, which is the purpose of deleting quotation marks ~ I!
The rules for deleting quotation marks are as follows (added by brother BAT!)
1. If there are quotation marks at the beginning and end of the string, delete the quotation marks at the beginning and the end of the string
2. If there are no quotation marks at the end of the string, delete the quotation marks at the beginning of the string
3. If there are quotation marks in the middle of the string, or if there are only quotation marks at the end, they are not deleted.
Tornado added: every head does not delete, there is a head even tail deletion.
2.% ~ fI- extends% I to a fully qualified pathname
Look at the example:
Save the code anywhere, and I'll put it on the desktop here.
FOR / F\ "delims==\"% I IN (# 39 control dir / b') DO @ echo%%~fi
Pause
The content displayed after execution is as follows
C:\\ Documents and Settings\\ Administrator\\ desktop\\ test.bat
C:\\ Documents and Settings\\ Administrator\\ desktop\\ test.vbs
When I change% ~ fi in the code directly to% I
FOR / F\ "delims==\"% I IN (# 39 control dir / b') DO @ echo%%i
Pause
After execution, the following is displayed:
Test.bat
Test.vbs
By comparison, we can easily see that there is no path, which is the function of "extending% I to a fully qualified pathname."
That is, if the content of the% I variable is a file name, he will print out the absolute path where the file is located, instead of just printing a file name, you will know it in the hands-on experiment!
3.% ~ dI- extends% I to only one drive letter
Look at the example:
The code is as follows, I will put it on the desktop for execution!
FOR / F\ "delims==\"% I IN (# 39 control dir / b') DO @ echo%%~di
Pause
After execution, my CMD shows the following
C:
C:
There are only two files on my desktop test.bat,test.vbs,%%~di function is that if the content of the variable% I is a file or directory name, he will put his file
Or the disk symbol where the directory is located is printed out!
4.% ~ pI- extends% I to only one path
This usage is the same as above, it only prints the path, not the file name.
FOR / F\ "delims==\"% I IN (# 39 control dir / b') DO @ echo%%~pi
Pause
I will not play the results, you see the results, the following several are such a usage, the code is given, you see the results!
5.% ~ nI- extends% I to only one file name
Print only the file name
FOR / F\ "delims==\"% I IN (# 39 control dir / b') DO @ echo%%~ni
Pause
% ~ xI- extends% I to only one file extension
Print only the file extension
FOR / F\ "delims==\"% I IN (# 39 control dir / b') DO @ echo%%~xi
Pause
7. The path extended by% ~ sI- contains only short names
Print an absolutely short file name
FOR / F\ "delims==\"% I IN (# 39 control dir / b') DO @ echo%%~si
Pause
8.% ~ aI- extends% I to the file attributes of the file
Properties of the print file
FOR / F\ "delims==\"% I IN (# 39 control dir / b') DO @ echo%%~ai
Pause
9.% ~ tI- extends% I to the date / time of the file
Date on which the print file was created
FOR / F\ "delims==\"% I IN (# 39 control dir / b') DO @ echo%%~ti
Pause
% ~ zI- extends% I to the size of the file
The size of the print file
FOR / F\ "delims==\"% I IN (# 39 control dir / b') DO @ echo%%~zi
Pause
In the above example,\ "delims==\" can be changed to\ "delims=\", that is, no delimiter
% ~ $PATH:I-find the directory listed in the path environment variable and extend% I
To the first fully qualified name found. If the environment variable name
If the file is not defined or the file is not found, this key combination will be extended to
Empty string
This is the last one, which is different from the ones above. I'll talk about it alone!
Then save the code as a batch and put it on the desktop.
@ echo off
FOR / F\ "delims=\"% I IN (\ "notepad.exe\") DO echo%%~$PATH:i
Pause
Tornado add: the above code shows the result as C:\\ WINDOWS\\ system32\\ notepad.exe
He means to search the notepad.exe file in the path specified in the PATH variable, and if there is a notepad.exe, it will print out his absolute path, and if not, print an error!
Chapter IV variables in batch processing
The variables in the batch are divided into two categories:\ "system variables\" and\ "custom variables\".
Now let's explain these two variables in detail!
I. system variables
Their values are automatically assigned by the system according to pre-defined conditions, that is, these variables have been defined by the system.
We don't need to assign a value to him, we just need to call it! I'll list them all!
% ALLUSERSPROFILE% returns the location of the all users profile locally.
% APPDATA% returns locally the location where the application stores data by default.
% CD% returns the current directory string locally.
% CMDCMDLINE% returns the exact command line used to start the current Cmd.exe locally.
The% CMDEXTVERSION% system returns the version number of the current Command processor extension.
The COMPUTERNAME% system returns the name of the computer.
The% COMSPEC% system returns the exact path to the command line interpreter executable.
The DATE% system returns the current date. Use the same format as the date / t command. Generated by Cmd.exe. Related
For more information about the date command, see Date.
The ERRORLEVEL% system returned the error code of the previous command. Errors are usually represented by a non-zero value.
The% HOMEDRIVE% system returns the local workstation drive letter connected to the user's home directory. Set based on the home directory value. Use
The household directory is specified in Local users and groups.
The% HOMEPATH% system returns the full path to the user's home directory. Set based on the home directory value. The user home directory is specified in Local users and groups.
The HOMESHARE% system returns the network path of the user's shared home directory. Set based on the home directory value. The user's home directory is
Specified in Local users and groups.
% LOGONSERVER% returns locally the name of the domain controller that validates the current login session.
The NUMBER_OF_PROCESSORS% system specifies the number of processors installed on the computer.
The OS% system returns the operating system name. Windows 2000 shows that its operating system is Windows_NT.
The PATH% system specifies the search path for executable files.
The% PATHEXT% system returns a list of file extensions that the operating system considers executable.
% PROCESSOR_ARCHITECTURE% system returns the chip architecture of the processor. Value: x86 or IA64 based on
Itanium
% PROCESSOR_IDENTFIER% system returned processor description.
The PROCESSOR_LEVEL% system returns the model of the processor installed on the computer.
The PROCESSOR_REVISION% system returns the version number of the processor.
% PROMPT% returns the command prompt settings for the current interpreter locally. Generated by Cmd.exe.
The% RANDOM% system returns any decimal number between 0 and 32767. Generated by Cmd.exe.
% SYSTEMDRIVE% system returned the root directory containing Windows server operating system (that is, system root)
The drive.
The SYSTEMROOT% system returns the location of the Windows server operating system root directory.
The% TEMP% and% TMP% systems and users return the default temporary directory used by the applications available to the currently logged in user.
Some applications require TEMP, while others require TMP.
The TIME% system returns the current time. Use the same format as the time / t command. Generated by Cmd.exe. Related
For more information about the time command, see Time.
% USERDOMAIN% returns locally the name of the domain that contains the user account.
% USERNAME% returns the name of the currently logged in user locally.
% USERPROFILE% returns the location of the current user's profile locally.
The WINDIR% system returns the location of the operating system directory.
With so many system variables, how do we know what their value is?
Enter echo WINDIR% in CMD
So you can display the value of a variable!
For example, we can do this if we want to copy files to the startup directory of the current account.
Copy d:\\ 1.bat\ "% USERPROFILE%\\" start menu\\ Program\ start\\ "
% USERNAME% returns the name of the currently logged in user locally. Note that directories with spaces are enclosed in quotation marks
There are also some system variables that represent the same meaning, or an operation!
They are 0% 1% 2% 3% 4% 5. Until% 9, there is still one% *.
% 0 is a bit special and has several layers of meaning. Let's first talk about the meaning of% 1% 9.
1 returns the first parameter of the batch
2 returns the second parameter of the batch
% 3mer% 9 infer according to this
Return batch parameters? How to return in the end?
Let's look at this example, save the following code as test.BAT and put it on disk C.
@ echo offecho 1 2 3 4echo cho 2echo 3echo 4
Enter CMD and enter cd c:\\
Then type test.bat. I'm the first parameter. I'm the second parameter. I'm the third parameter. I'm the fourth parameter.
Notice the space in the middle, and we will see the result like this:
I'm the first parameter. I'm the second parameter. I'm the third parameter. I'm the fourth parameter.
I'm the first parameter.
I'm the second parameter.
I'm the third parameter.
I'm the fourth parameter.
Compared with the code, 1 is "I am the first parameter" and 2 is "I am the second parameter"
How do you understand?
These% 1 and% 9 allow batch processing to run with parameters, greatly improving batch processing capabilities!
There is another% * what is he? It's not very useful, it just returns parameters, but it returns all the parameters at once, and you don't have to enter% 1% 2 to determine one by one.
Examples
@ echo off
Echo% *
Also save as test.bat and put it on disk C.
Enter CMD and enter cd c:\\
Then type test.bat. I'm the first parameter. I'm the second parameter. I'm the third parameter. I'm the fourth parameter.
You can see that he shows all the parameters at once.
Okay, now let's talk about the special% 0.
% 0 this is not the value of the return parameter, it has two meanings!
First meaning: return to the absolute path where the batch is located
Example:
@ echo off
Echo 0
Pause
Save it as test.BAT and run it on the desktop, and the result is as follows
\ "C:\\ Documents and Settings\\ Administrator\\ Desktop\\ test.bat\"
He prints out the path where the current batch is executed, which means to return the absolute path where the batch is located
The second meaning: infinite loop execution of BAT
Example:
@ echo off
Net user
% 0
Save as BAT and it will loop through the net user command indefinitely until you stop it manually.
Tornado added: in fact,% 0 is the parameter before the first parameter% 1, which is, of course, the batch file name (including path).
These are some of the system variables in the batch, and there are other variables that also represent some functions.
Those in the FOR command are those that have already been said by the FOR variable, so let's not talk about it.
II. Custom variables
Therefore, the name implies that a custom variable is a variable that we assign a value to it.
To use custom variables, you have to use the set command. Look at the example.
@ echo off
Set var=, I'm worth it.
Echo var%
Pause
Save as BAT execution, we will see a\ "I am value\" returned in CMD.
Var is the variable name, and the value to be given to the variable is changed to the right of the = sign.
This is the easiest way to set variables.
If we want the user to enter the value of the variable manually instead of specifying it in the code, we can use the / p parameter of the set command
Example:
@ echo offset / p var= Please enter the value of the variable echo var%pause
To the right of the var variable name = sign is the prompt, not the value of the variable.
The value of the variable is entered by ourselves with the keyboard after we run it!
Chapter V detailed explanation of set order
In the previous post, I briefly introduced the role of SET in setting custom variables, and now let's talk about other functions of set.
First, set custom variables with the set command
Displays, sets, or deletes the cmd.exe environment variable.
SET [variable] = [string]
Variable specifies the name of the environment variable.
String specifies a series of strings to assign to the variable.
To display the current environment variable, type SET with no parameters.
The SET command does not allow variable names to have an equal sign.
Note: the following usage clears the value of the variable variable, making it undefined.
SET variable=
There is no sign after the above equal sign. If it is written as SET variable=\ "\", the value of the variable is not empty, but is equal to two quotation marks, that is,\ "\".
Example:
@ echo offset var= I am worth echo% var%pause
Look at set var= I am the value, this is how BAT sets variables directly in the batch!
Set is the command var is the variable name = sign to the right of\ "I am the value\" is the value of the variable
To refer to this change in the batch, expand the var variable name with two% (% sign), such as% var%
SET can also provide an interactive interface for users to enter the value of the variable themselves, and then we will do the corresponding operation according to this value. Now I will talk about the syntax of SET, just add a\ "/ P\" parameter!
SET / P variable= [promptString]
Example:
@ echo offset / p var= Please enter the value of the variable: echo you entered% var%~_~pause
Set / p is the command syntax var is the variable name = sign to the right of\ "Please enter the value of the variable:\", this is the prompt, not the value of the variable!
After running, we type 1 directly after the prompt, and a line will be displayed that you have entered 1 ~ _ ~
Now let's talk about the other functions of SET.
Use set /? Looking at SET's help, we found that SET, in addition to what I mentioned above,
SET [variable= [string]]
SET / P variable= [promptString]
In addition to these two grammars, there are the following grammars:
SET / An expression
Environment variable substitution has been enhanced as follows:
% PATH:str1=str2%
% PATH:~10,5%
% PATH:~-10%
% PATH:~0,-2%
What is the use of this kind of grammar? Let's explain one by one!
Second, use set command to do simple calculation.
Syntax: SET / An expression
The / A command line switch specifies that the string to the right of the equal sign is the evaluated numeric expression. The expression
The evaluator is simple and supports the following operations in descending order of priority:
()-grouping
! ~-- unary operator
* /%-arithmetic operator
+-arithmetic operator
>-binary logic shift
-binary bitwise "and"
^-binary bitwise "different"
| |-binary bitwise "OR"
= * /% = + =-- arithmetic assignment
= ^ = =-binary operation assignment
,-expression delimiter
If SET / An is executed on a command line other than the command script, it displays the last value of the expression.
Except for hexadecimal with 0x prefix, octal with 0 prefix, the numeric value is decimal.
Therefore, 0x12 is the same as 18 and 022. Note that octal formulas can be easily confused:
08 and 09 are invalid numbers because 8 and 9 are not valid octal digits.
These are the contents of the system help, look a little dizzy, it doesn't matter, let me briefly explain:
The / A parameter of set allows SET to support mathematical symbols for addition and subtraction and other mathematical operations!
Note: the general operation is often a decimal operation, if the leftmost numeric string is 0, it will be considered octal, resulting in an error. For example, numbers such as 0812 cannot participate in decimal operations, and the conversion method is: 10812-10000
Example:
Set aa=0812
Set / an aa=1%aa%-10000
Echo aa%
The result is: 812
Example:
@ echo offset / p input= Please enter the calculation expression: set / a var=%input%echo calculation result:% input%=%var%pause
The above example is designed by tornadoes and is easy to use. please take a look at the following operations:
Note: DOS calculation can only operate on integers, accurate to integers.
Please enter the calculation expression: 1 "9" 20 "30-10"
Calculation result: 1: 9: 20: 30-10: 50
Please press any key to continue. . .
Please enter an expression for the calculation: 10 stroke division can only be accurate to an integer
Calculation result: 10 inch 3 inch 3
Please press any key to continue. . .
Please enter the calculation expression:-100 "6" negative number
Calculation result:-100mm 62m / m 38
Please press any key to continue. . .
Please enter the calculation expression: 100% remainder
Calculation result: 100% 331
Please press any key to continue. . .
Note: the above remainder operator% must be written as%% in the batch program.
Please enter the calculation expression: (25075) * 2 / (1505) # parentheses
Calculation result: (25: 75) * 2 / (15: 5) = 10
Please press any key to continue. . .
Please enter the calculation expression: 1234567890 "9876543210 # range
Invalid number. Digital accuracy is limited to 32 bits.
Calculation result: 123456789098 76543210 =
Please press any key to continue. . .
Note: the above calculation process shows that the DOS calculation can only be accurate to 32 bits, which refers to the binary 32 bits, where the highest bit is the sign bit (0 is positive, 1 is negative) and the low bit 31 is the value. Change 31 1s to decimal 2147483647, so the range of valid values calculated by DOS is-2147483648 to 2147483647. An error occurs when the value is beyond this range. Please see the following calculation process:
Please enter the calculation expression: 2147483647-minus the maximum value minus 1, the value is valid
Calculation result: 2147483647-1147483646
Please press any key to continue. . .
Please enter the calculation expression: 2147483647 maximum plus 1, error, the result is the minimum
Calculation result: 21474836477147483648
Please press any key to continue. . .
Please enter the calculation expression:-2147483648-1 # minimum minus 1, error, the result is the maximum
Calculation result:-2147483648-1147483647
Please press any key to continue. . .
A 4 is displayed after running set / an axiom 1, 1, 2, 2, 1, 3, 1, but we use the
If you look at the result after echo% a% b% c%, you will find that other mathematical operations are also effective! this is the expression separator\ "funny\" sign.
It works!
Sometimes we need to add and subtract directly from the original variable to use this syntax.
A syntax such as set / a var+=1 corresponds to the original syntax set / a var =% var% + 1
It's all the same result, and we're doing mathematical operations on the values of the original variables, but it's a little easier to write this way.
One more:
Set / a var*=2
Everything else is used in this way, as long as there is this grammar in the help!
In addition, some use logic or remainder operators, and these symbols will report errors according to the above method of use.
For example, if we type set / a var=1 1\ "and operation\" in CMD, it will not display as 1, but will report an error.
Why? For such logical or remainder operators, we need to enclose them in double quotation marks, or we can use the escape character ^. See the example.
Set / a var= 1\ "\" 1 so that the result is displayed, other logic or remainder operator usage
Set / a var= 1\ "+\" 1 heterooperation
Set / a var= 1\ "%\" 1 Modulus Operation
Set / a var= 3\ "\" 2 right shift operation, the binary of 4 is 100,2 bits of right shift is 1, and the result is 1.
Tornado added: all bitwise calculations need to be converted to binary.
Thinking question: find the n power of 2
Reference answer:
@ echo offset / p n = Please enter the power of 2: set / a num= 1 ^ .bat > .cmd, that is, if there are four types of files with the same file name in the same directory, DOS executes name.com when only the file name is typed, and if you need to execute the other three files, you must specify the full name of the file, such as name.bat.
This is a free green tool that is only 5.43K in size and can be run on the command line of a pure DOS or DOS window. Usage: Bat2Com
FileName, which generates an executable file named FileNme.com in the same directory, and executes in the same way as the original .bat file.
IX. Time delay
Refer to [Hero] tutorial in this article
What is time delay? As the name implies, the execution of one command is delayed for a period of time before the next command is executed.
For the application of delay, see the following section: "Simulation Progress Bar".
1. Delay by using ping command
Example:
@ echo offecho before delay:% time%ping / n 3 127.0.0.1 > nulecho after delay:% time%pause
Explanation: the "/ n" parameter of the ping command is used to indicate how many requests to send to the specified ip. In this example, three requests are sent to the native ip (127.0.0.1). 127.0.0.1 can be abbreviated to 127.1. "> nul" is to block out what is displayed by the ping command.
2. Delay by using for command
Example:
@ echo offecho before delay:% time%for / l% I in do echo% I > nulecho after delay:% time%pause
Explanation: the principle is very simple, that is, to achieve the purpose of delay by using a count loop and shielding what it shows.
3. Using the vbs delay function, the accuracy is millisecond and the error is less than 1000 milliseconds.
Example:
Echo offecho% time%call: delay 5000echo% time%pauseexit:delayecho WScript.Sleep% 1 > delay.vbsCScript / / B delay.vbsdel delay.vbsgoto: eof
The run shows:
10:44:06.45
10:44:11.95
Please press any key to continue. . .
The above running results show that the actual delay is 5500 milliseconds, and the extra 500 milliseconds takes time to create and delete temporary files. The error is within a second.
4. Only batch commands are used to achieve arbitrary time delay with an accuracy of 10 milliseconds and an error of less than 50 milliseconds.
Deferred operations can be achieved with only batch commands.
Example:
@ echo offset / p delay= Please enter the number of milliseconds to delay: set TotalTime=0set NowTime=%time%:: read start time The time format is: 13:01:05.95echo program start time:% NowTime%:delay_continueset / a minute1=1%NowTime:~3,2%-100:: read start time set / a second1=1%NowTime:~-5,2%%NowTime:~-2%0-1000000 set: change the number of seconds of the start time to milliseconds set NowTime=%time%set / a minute2=1%NowTime:~3,2%-100:: read the minutes of the current time set / a second2=1%NowTime: ~-5 time%echo 2% delay% milliseconds echo actual delay time: change the number of seconds of the current time to milliseconds set / a TotalTime+= (% minute2%-%minute1%+60)% 60*60000+%second2%-%second1%if% TotalTime% lss% end time:% time%echo set delay time:% NowTime millisecond echo actual delay time:% NowTime millisecond pause
The run shows:
Please enter the number of milliseconds to delay: 6000
Start time of the program: 15Rd 32RL 16.37
End time of the program: 15Rd 32RL 22.37
Set delay time: 6000 Ms
Actual delay time: 6000 Ms
Please press any key to continue. . .
The principle of implementation: first set the number of milliseconds to delay, and then accumulate the time with a loop until the cumulative time is greater than or equal to the delay time.
Error: windows system time can only be accurate to 10 milliseconds, so there may be a 10 millisecond error in theory.
After testing, when the delay time is more than 500 milliseconds, the above delay program generally has no error. When the delay time is less than 500 milliseconds, there may be tens of milliseconds error. Why? Because the delay program itself has running time, and the system time can only be accurate to 10 milliseconds.
For ease of reference, change the above example to the form of subroutine invocation:
@ echo offecho program start time:% Time%call: delay 10echo actual delay time:% totaltime% millisecond echo program end time:% time%pauseexit::- is the delay subroutine -: delay@echo offif\ "% 1\" =\ "\" goto: eofset DelayTime=%1set TotalTime=0set NowTime=%time%:: read start time The time format is: 13:01:05.95:delay_continueset / a minute1=1%NowTime:~3,2%-100set / a second1=1%NowTime:~-5,2%%NowTime:~-2%0-100000set NowTime=%time%set / a minute2=1%NowTime:~3,2%-100set / a second2=1%NowTime:~-5,2%%NowTime:~-2%0-100000set / a TotalTime+= (% minute2%-%minute1%+60)% 60*60000+%second2%-%second1%if% TotalTime% lss% DelayTime% goto delay_continuegoto: EofX, simulation progress bar
Here is a program to simulate the progress bar. If you apply it to your own program, you can make your program more beautiful.
The @ echo offmode con cols=113 lines=15 color 9fclsecho.echo program is initializing. . .echo.echo ┌──┐ set/p= ■ run-> enter cmd-> edit-> ctrl+p (meaning special characters are allowed)-> press ctrl+a to display the smiley face pattern.
(if you want to continue entering special characters, press ctrl+p again, and then ctrl+ a letter)
The above is the input method of special characters, selected from the Hero tutorial, it is very useful. That is, use the editor program edit to enter special characters, then save them as a text file, then open the file under windows and copy the special symbols in it.
Some simple special symbols can be entered directly in the dos command window and saved as a text file with redirection.
Example:
C: > ECHO ^ G > temp.txt
"^ G" is inputted with Ctrl+G or Alt+007. Entering multiple ^ Gs can produce multiple tones.
The application of special characters is also very interesting. Here is just one example: backspace key.
The Backspace key means to delete the character on the left. This key cannot be entered normally in the document, but can be typed and copied through the edit editor. That is, "".
Using the backspace key, you can design flashing text effects.
Example: text flicker
@ echo off:startset/p= has bright moonlight in front of the bed nul:: setting delay time set/p a =
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.