Windows bat Learning

Source: Internet
Author: User

I suddenly fell in favor of windows batch processing, and suddenly got used to starting the program under cmd, And suddenly got used to mkdir, cp, rm .....

I couldn't help but be tempted. I used a few days to carefully study the syntax structure of bat. I mainly referred to the two Word documents on the Internet, and I felt that they were well written:

Windows_bat .docx (33kB) windows_batbat .doc (175KB)

The first word document mainly describes the usage of some frequently-used commands in batch processing. Each Command is very detailed. after learning the simple syntax structure of batch processing, it will be much better to use it later.

The second word document is a bit empty. The first part of the lecture is easy to understand and suitable for beginners. The intermediate part of the lecture is more detailed and in-depth, mainly including the use of set, choice, if, for, and built-in symbols, it is my focus, advanced syntax. In the last 1/3, there was a very large batch processing program, which was used to optimize the XP system. It was basically a registry operation and had little value for learning batch processing, can be skipped.

You can first take the first 1/3 of the second article to learn about the basic syntax structure, and then pay attention to the 1/3 section in the middle to enhance the use of if, for, choice, set, etc, these are the essence of batch processing. If you do not know what to do when writing your own batch processing, you can look at the first word document and browse the basic commands, you can get a general idea of what each command can do. Practice makes perfect.

It seems that you need to know what commands can be used to solve the problem. As for the command syntax, you just need to directly view the Command help. The help is the most comprehensive document.

Set: defines variables, cut strings, and arithmetic operations

For: String traversal, file traversal, loop count control, cut string

If: Condition judgment

Goto: Tag jump

Call: bat call or label call

Choice: A required notebook

The following is a summary of my personal experience. I think that my memo, I prefer ue, And I will directly use txt:

Windows bat:
1. echo indicates the character after the command is displayed.
2. echo off indicates that after this statement, all running commands do not display the command line itself.
3, @ is similar to echo off, but it is added at the beginning of each command line, indicating that the command line of this line is not displayed at runtime (only the current line can be affected ).
4. call calls another batch file (if you do not need to call another batch file directly, after the batch processing file is executed, the current file cannot be returned and Subsequent commands of the current file can be executed)
5. Running pause will pause batch processing and display "Press any key to continue..." or "Press any key to continue..." on the screen ..." Prompt, wait for the user to press any key to continue.
6. rem indicates that the character after this command is interpreted as a line (comment). If it is not executed, it will only be used for future reference (equivalent to a comment in the program ).
Example:
@ Echo off
Rem echo off usage
Pause
7, % [1-9] indicates a parameter. A parameter is a string separated by spaces (or tabs) after the file name is added to a batch file. Variables can be changed from % 0 to % 9.% 0 indicates the Batch Processing Command itself. Other parameter strings are represented in the order of % 1 to % 9.
8,: choice: CHOICE [/C choices] [/N] [/CS] [/T timeout/D choice] [/M text]
/M prompt text,/C option,/T timeout event,/D timeout is selected by default
CHOICE/c ync/M "OK, Press Y or N, or cancel, press C"
Choice/C dimethyl/M "defrag, mem, end"
If errorlevel 3 goto end
If errorlevel 2 goto mem
If errorlevel 1 goto defrag
9. Microsoft has the following built-in characters which cannot be used between the created file names.
Con nul aux \/| & amp; ^ & gt; <*
Special symbols. do not include "", or add ^ escape
> Create an object
> Append to a file
, Which is the same as the default delimiter of space.
; Annotation, indicating that it is followed by Annotation
: Label Function
| MPs queue operations
This method can be used to execute multiple commands at the same time, regardless of whether the command is successfully executed.
Dir c: \ *. exe & dir d: \ *. exe & dir e: \ *. exe
& Usage: The first command & the second command [& the third command...]
When an erroneous command is executed, the subsequent commands will not be executed. If no error occurs, all commands will be executed;
| Usage: The First Command | the second command [| the third command...]
When a correct command is executed, the subsequent commands are not executed. If no correct command is displayed, all commands are executed;

10. You can select an if statement.
1. String comparison
The if statement can only judge whether two characters (strings) are the same and their order is sequential. The command format is:
IF [not] string1 compare-op string2 command1 [else command2]
The comparison operator compare-op has the following types:
=-Equal
EQU-equal
NEQ-not equal
LSS-less
LEQ-less than or equal
GTR-greater
GEQ-greater than or equal
If you select switch/I, the string is case-insensitive. If you select not, the result is logically non-deterministic.
String comparison example:
========================================================== ========
@ Echo off
Set str1 = abcd1233
Set str2 = ABCD1234
If % str1 % = % str2 % (the echo string is the same !) Else (echo strings are different !)
If/I % str1 % LSS % str2 % (echo str1 ^ <str2) else (echo str1 ^> = str2)
Echo.
Set/p choice = show current time? (Y/n)
If/I not % choice % EQU n echo current time: % date % time %
Pause> nul
========================================================== ========
For the last if judgment, when we input n or N, the effect is the same, and no time is displayed. If we disable/I, the time will still be displayed when N is entered.
Note the following details: 1-echo str1 ^ <str2 and echo str1 ^> = str2; 2-echo ..
2. Existence judgment
The function of existence determination is to determine whether a file or folder exists. The command format is:
IF [NOT] EXIST filename command1 [else command2]
========================================================== ========
@ Echo off
If exist % 0 echo file % 0 exists!
If not exist % ~ Df0 (
Echo folder % ~ Df0 does not exist!
) Else echo folder % ~ Df0 exists!
Pause> nul
========================================================== ========
Note the following:
1-judgment can be performed to determine files or folders;
2-% 0 indicates the full name of the batch processing (including drive letter, path, file name and extension type );
3-% ~ Df0 is a correction to % 0. It only retains its drive letter and path. for more information, see /?, Belongs to the scope of advanced batch processing;
4-pay attention to the multi-row Writing of if Statements, multi-row writing requires that the Left brackets of command1 must be the same line as if, else must be the same as the right brackets of command1, and command2 must be the same as else, command1 and command2 can have any number row, that is, the command can be a command set.
3. Definition judgment
The definition judgment function is to determine whether a variable exists, that is, whether it has been defined. The command format is:
IF [not] DEFINED variable command1 [else command2]
Example of existence judgment:
========================================================== ========
@ Echo off
Set var = 111
If defined var (echo var = % var %) else echo var is not defined yet!
Set var =
If defined var (echo var = % var %) else echo var is not defined yet!
Pause> nul
========================================================== ========
The comparison shows that "set var =" can cancel the variable and reclaim the memory space occupied by the variable.
11,
1. No Switch
A for statement without a switch can be used to loop within a set range. It is the most basic for loop statement. The command format is:
FOR % variable IN (set) DO command
Here, % variable is the writing format in the batch processing program. In DOS, it is written as % variable, that is, there is only one percentage sign (%); set is the loop range that needs to be set, similar to the Circular Variable in C language, the command after do is the command executed by the loop, that is, the loop body.
Example of a for statement without a switch:
========================================================== ========
@ Echo off
For % I in (a, "B c", d) do echo % I
Pause> nul
========================================================== ========
2. Switch/L
For statements with a switch/L can be cyclically set to directly control the number of loops. The command format is:
FOR/L % variable IN (start, step, end) DO command
Here, start is the initial value of the start count, step is the value of each increment, and end is the end value. When end is less than start, the step must be set to a negative number.
Example of a for statement containing the switch/L (create five folders ):
========================================================== ========
@ Echo off
For/l % I in (1, 2, 10) do md % I
Pause
========================================================== ========
In the preceding example, five folders are created with names 1, 3, 5, 7, and 9. It can be found that the end value of % I is not the value of end 10, but not greater than the number of end.
3. Switch/F
The for statement containing the switch/F has the most powerful functions. It can operate strings, operate the return values of commands, and access ASCII files on hard disks, for example, txt files. The command format is:
FOR/F ["options"] % variable IN (set) DO command
Set is one of ("string", 'command', and file-set); options is (eol = c, skip = n, delims = xxx, tokens = x, y, m-n, usebackq. For the meanings of each option, see for/f. Generally, three options are used: skip, tokens, and delims.
For statement with switch/F:
========================================================== ========
@ Echo off
Echo ** No Options:
For/f % a in ("1, 2, 10") do echo a = %
Echo ** Options tokens ^ & delims:
For/f "tokens = 1-3 delims =," % a in ("1, 2, 10 ") do echo a = % a B = % B c = % c
Pause
========================================================== ========
@ Echo off
Echo files in this folder include:
For/f "skip = 5 tokens = 3 * delims =" % a in ('dir') do (
If not "% a" = "<DIR>" if not "% B" = "Byte" if not "% B" = "available Byte" echo % B
)
Pause
========================================================== ========
@ Echo off
Echo files in this folder include:
Dir> c: \ file.txt
For/f "skip = 5 tokens = 3 * delims =" % a in (c: \ file.txt) do (
If not "% a" = "<DIR>" if not "% B" = "Byte" if not "% B" = "available Byte" echo % B
)
Del c: \ file.txt
Pause
========================================================== ========
In the following two examples, delims = in options can be deleted, because the delims value is blank by default when/F is added.
The asterisks of the last character in the symbol string,
Then the extra variable will be resolved after the last symbol
Distribute and accept reserved text of rows. In this example, you can also change to 4, but the file with spaces in the file name can only display the previous section of space
At the same time, we can also see that the command after the do statement of the for statement can also be split, you only need to ensure that the left parenthesis of the command and do are in the same line.
4. Switch/D or/R
A for statement containing/D or/R is a command related to a directory or file, which is rarely used in general. Commands with switch/R are sometimes used to search for a file or folder by traversing the folder, so this example is listed.
Example of a for statement with a switch/R (Folder traversal ):
========================================================== ========
@ Echo off
Setlocal enabledelayedexpansion
FOR/R d: % I IN (.) DO (
Set dd = % I
Set "dd =! Dd :~ 0,-1! "
Echo! Dd!
)
Pause
Exit
========================================================== ========

----------------------------------- 13:11:04 -----------------------------------
Windowsbat learning summary:
If the batchcompute command returns 0 to be successful, sometimes it seems that the command is correct, but an error is always reported. Add parentheses to the command and try again.
For the if statement, the else statement is always enclosed in parentheses.

1, @, rem,:, set, echo, pasue, goto, exit, call, choice, if,,
2. & continuous execution, regardless of the correct error, & continuous execution until the error occurs. | continuous execution until the correct execution ends.> create a file,> append to a file
&, &, |,
True & echo good returns 0, errorlevel
False & echo good returns 1,
>,>>
Echo good> file; create
Echo good> file; append

3. choice statement Structure
Choice/c ync/t 5/d y/m "please choice yes, no, cancel"
4. if statement Structure
1. String comparison
Set var1 = "1234A"
Set var2 = "1234a"
If/I % var1 % EQU % var2 % (echo equal) else (echo not equal)
2. Existence judgment
If exist % 0 (echo exist % 0) else (echo not exist % 0)
3. Definition judgment
Set var = "var"
If defined var echo (var = % var %) else echo "var not defined"
Set var =
If defined var echo (var = % var %) else echo "var not defined"
4. choice judgment

Errorlevel's if judgment is greater than or equal to, please note, the best is that the goto statement jumps out better labels

CHOICE/c ync/M "OK, Press Y or N, or cancel, press C"
Choice/C dimethyl/M "defrag, mem, end"
If errorlevel 3 echo end
If errorlevel 2 echo mem
If errorlevel 1 echo defrag
5. for statement Structure
1. No Switch
Directly traverse the string, separated by spaces. When the string to be traversed has spaces, "" is also included in the string.
Set list = how do "you suck" do OK
For % I in (% list %) do echo I = % I
Directly traverse strings and separate them with commas (,) to process strings with spaces.
Set list = how, do, you suck, do, OK
For % I in (% list %) do echo I = % I
2. Switch/L
: Start is the initial value of start count, step is the value of each increment, and end is the end value. When end is less than start, the step must be set to a negative number.
: For Loop with a fixed number of cycles
For/L % I in (1, 3, 15) do echo I = % I
3. Switch/F
It can be used to intercept a part of a string, which is separated by delims characters.
For/f % a in ("1, 2, 10") do echo a = %
For/F "tokens = 1-3 delims =," % a in ("1, 2, 10 ") do echo a = % a B = % B c = % c
I feel like I may be using a common for loop:
Set list = how do "you suck" do OK; string split separated by Spaces
For % I in (% list %) do echo I = % I

Set list = how, do, you suck, do, OK; string split separated by commas (,). The quotation marks are removed.
For % I in (% list %) do echo I = % I

Set list = how do you suck do OK
For % I in (% list %) do echo I = % I

For/L % I in (1, 3, 15) do echo I = % I; for loop control times

For/F "tokens = 1-3 delims =," % a in ("1, 2, 10 ") do echo a = % a B = % B c = % c; The for statement for intercepting strings should not be considered as a for Loop
Cls

Advanced usage:
Skip indicates that the first five rows are skipped. tokens indicates that the third column is selected as % I, and all the following columns are % j. if statements can be used to determine multiple condition connections.
@ Echo off
Echo:
For/F "skip = 5 tokens = 3 * delims =" % I in ('dir') do (
: Echo "I = % I, j = % j"
If not "% I" = "<DIR>" if not "% j" = "Byte" if not "% j" = "available Byte "(
Echo % j
)
)


----------------------------------- 2013/5/28 13:46:42 -------------------------------
Usage:
Bat:
Set var = % str ::= 2% indicates to replace: In the string abc: de with 2;
Returns the string length.
Set str = teststring
: Nextlost
If not "% str %" = ""(
Set/a num + = 1
Set "str = % str :~ 1%"
Goto nextlost
)

Test. bat: the input parameter is c: \ temp \ test1.txt.
The following 1 should refer to the first parameter.
Echo % ~ D1 => c:
Echo % ~ Dp1 => c: \ temp \
Echo % ~ Nx1 => test1.txt
Echo % ~ N1 => test1
Echo % ~ X1 =>. txt
Cho current directory path: % ~ Dp0
Speech:
Mshta vbscript: createobject ("sapi. spvoice"). speak ("Learn Merry Christmas and Happy New Year! ") (Window. close)

For Loop traversal uses a string separated by spaces to process each string accordingly.
: Nextfor
FOR/F "tokens = 1, *" % I in ("% serviceslist %") do (
Set torestart = % I
Set serviceslist = % j
If not "% serviceslist %" = ""(
Call: restartprog
Goto: nextfor
)
)
Goto: end
: Function call demonstration
: ----------- Restartprog begin ---------------
: Restartprog
Echo "restartprog: % torestart %"
Goto: EOF
: ----------- Restartprog end ----------------

Set Calculation evaluation:
Set var = 10
Set/a var + 8*2 + var * 2
Set/a "var + 8*2 + var * 2> 2"

Extended delayed environment variables:
Setlocal enabledelayedexpansion
Set VAR = before
If "% VAR %" = "before "(
Set VAR = after
If "! VAR! "=" After "@ echo If you see this, it worked
)
Command extension ??? : Not clear yet
Echo % random %
Echo % cd %
Set v
Set p

Truncation string:
Set var = 10203040
The first digit is the position, the second position is the length, and if there is no second position, the default position is the end. If the first position is a negative number, the opposite direction is the position. The position starts from 0.
Echo % var :~ -4,3%
Echo % var :~ 0%
Echo % var :~ 1%
Echo % var :~ -2%
Replace string
Echo % var: 0 = kkk %; 0 is replaced with kkk
Echo % var: 10 = kkk %; 10 is replaced with kkk
Echo % var: 20 = kkk %
Echo % var: * 20 = kkk %; replace 20 strings with kkk before 20.

Related Article

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.