Analysis of windows bat batch processing syntax

Source: Internet
Author: User
Tags echo command ultraedit

I haven't written a blog for a long time. I haven't read much about it in this period of time, but I always feel that I have not finished a job. So I will write down my summary.
Section 1 describes windows batch processing.
This is because I learned how to work in windows with my colleagues. I gradually needed some batch processing functions, so I took a few days to study it. I think the most important feature of a document is to forget it. I have selected many document examples and I am sorry that I have not been able to identify the source in detail for a long time. For my personal use, many unnecessary things in this example are simplified by me, and some important things are described too detailed by me. Let's take a look.
To put it simply, from the perspective of the original batch processing language, the commonly used C language includes input and output, defining variables, sequence, loop, and condition judgment. This is the root of any language, and I will describe it based on these classes.

Summary:

To run the batch processing command, first create a txt file and change its suffix. bat. For example, name it my. bat, open cmd, and switch to my. bat directory, enter my. bat to run my. the command written in bat. For the simplest test example, add echo hello world to display hello world in the cmd window.
Category Description: Help :/?

Command /? View the help of the corresponding command, which is the most authoritative at any time.
Note: Command, echo off command

Comments in the program are quite useful. Line comments are added at the beginning of the line:, the example is as follows:
: This is a comment.
@ Echo off indicates that the command itself is not displayed when the command is executed.
Variable: set command

Set var = "c: \ a.txt"
Echo % var %
Output: echo command, printed directly to the console

Echo Hello World
Enter the choice command to switch to different processes based on user input.

Carefully analyze this example and use the choice command to read different user input. The following uses goto to switch to different processing procedures based on different user input.
Goto is to jump to different labels. The label is defined as: (colon) followed by the label name. For example, the following labels are no,: yes,: cancel, and: end. Why should a goto end be added for each label? This is because after the jump to the label, the program starts to execute in sequence. If the jump is not performed, the program continues to run to the next label. A label is just a tag. Unlike a function, it has its own scope, which is included in braces. The label has no range. It is just a tag. Remember to remember. Useful examples.
CHOICE/C
YNC/M "OK, Press Y, no press N, or cancel press C"
If errorlevel 3 goto cancel
If errorlevel 2 goto no
If errorlevel 1 goto yes
: No
Echo no way
Goto end
: Yes
Echo yes, please
Goto end
: Cancel
Echo alread canceled.

: End
Passing parameters: % 1, % 2..., % 9 correspond to parameters passed by the user through commands.

Echo % 1, % 2, % 3 in the program, and mybat param1 param2 param3 in the called place to see if param1, param2, param3 is printed out?
This is similar to the option in the command. This is why many commands have options.
I would like to provide you with a frequently used function.
I like to use ultraedit to edit daily work records and logs, including the blog I am writing, which is also edited using ultraedit, which is short for ue.
So I searched the ue installation directory. My installation directory is as follows: C: \ Program Files (x86) \ IDM Computer Solutions \ UltraEdit \ Uedit32.exe, I also studied how to use the command to start the application and find the start command. So I used start "" C: \ Program Files (x86) \ IDM Computer Solutions \ UltraEdit \ Uedit32.exe "to start ue through the command line, but this command is too long, not easy to remember. Through bat learning, we can know that this command can be run in a. bat file. So I created a ue. bat file with the following content:

@ Echo off ::
Start "" C: \ Program Files (x86) \ IDM Computer Solutions \ UltraEdit \ Uedit32.exe"
But I cannot switch to ue every time. execute ue in the bat directory. the bat command creates a separate directory and adds the directory to the environment variable. In this way, the command line can search for the files in this directory and set ue. put bat in this directory. In this case, I only need to break the ue(ue.exe, ue. bat, and other files will automatically match ue.exe under startup. Ue can be used to open files. I guess ue should be able to pass parameters. Add the % 1 parameter to the command above, that is, start "" C: \ Program Files (x86) \ IDM
Computer Solutions \ UltraEdit \ Uedit32.exe "% 1, then enter ue blog.txt In the cmd command line. If blog.txt is found in the current directory, ue will automatically open it. If no, it automatically creates a new blank file. Very easy to use. This is an amazing use of parameters passed by applications. The above start command can be extended. common software such as QQ, vs2008, vc, chrome and so on all use vc. bat, qq. bat, Desktop shortcuts are not very useful.
Condition determination: if command

========================================================== ========
@ Echo off
Set str1 = abcd1233
Set str2 = ABCD1234
If % str1 % = % str2 % (
The echo string is the same!
) Else (
Echo strings are different!
)
========================================================== ========
Pay attention to the above if and else syntax structure. else cannot be the first line. This is so disgusting that I often encounter syntax errors. Later I basically used the above as a template. Even if a sentence needs to be executed, I also included (), and the syntax was written according to the above description. Easy to remember.
If judgment involves several situations
1. errorlevel judgment, as shown in the above example.
2. Comparison and judgment are commonly used as follows:
=-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.
3. There is a judgment, that is, if exists file1 echo "file1 exists" syntax structure to determine the existence of a file or directory.
4. Define and determine whether a variable exists, that is, whether it has been defined. The command format is:
IF [not] DEFINED variable command1 [else command2]

Loop:

1. 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 C Language
And 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) one or more groups
. 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
========================================================== ========

4. In summary, there are three commonly used methods. The unswitched mode is mainly used to loop the Set range, and there are few applications.
L is often used to set the number of loops. for example, if the number of loops is 10 times, you can for/l % I in (, 10) do (command) to loop 10 times.
F is often used to intercept strings. However, for, it can intercept command results in batches. In can use strings, command results, or files, which is quite powerful and hard to use.
The following example makes you feel a little bit:
========================================================== ========
@ 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
========================================================== ========
In this example, skip = 5 indicates that the first five characters are to be skipped, delims = indicates that the first five characters are to be skipped, and delims = indicates that the first five characters are to be skipped, and the last group (* indicates the first group to the last group ). the third group corresponding to % a and the Group * corresponding to % B.
There are also switch/R,/D, which I have never used or have a deep understanding.
Truncation path parameters:

Intercept input parameters with paths
Test. bat: assume that the input parameter is c: \ temp \ test1.txt.
The corresponding truncation is as follows: The following 1 indicates that it corresponds to % 1, of course, it can be 2, 3, and so on, and corresponds to the input parameter.
Echo % ~ D1 => c:
Echo % ~ Dp1 => c: \ temp \
Echo % ~ Nx1 => test1.txt
Echo % ~ N1 => test1
Echo % ~ X1 =>. txt
Cho current directory path: % ~ Dp0
Voice:

Mshta vbscript: createobject ("sapi. spvoice"). speak ("Learn Merry Christmas and Happy New Year! ") (Window. close)

String processing:

Truncation string:
Set var = 10203040
The first digit is the position, where the screenshot starts, and the second digit is the length of the screenshot.
If the first digit is a negative number, it indicates the position in the opposite direction. For example,-4 indicates that it starts from the fourth to the last character.
If there is no second number, it indicates the maximum length that can be reached. The position starts from 0.
Echo % var :~ -4, 3%; truncates three characters from the position of the last and fourth characters.
Echo % var :~ 0%; Starting from a positive number of 0th locations, that is, the total length.
Echo % var :~ 1%; truncates all characters except the first character from the first positive number
Echo % var :~ -2%
From the position of the last 2nd characters, 2 characters are taken (from left to right, there are only 2 Characters at most ).
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.

Simple complaints:

This article mainly describes the basic syntax of bat and does not focus much on commands. Using bat on the basis of the command will actually get twice the result with half the effort. You can use it only when batch processing or repetitive work is required. You can simply complete the simple work by yourself. I personally think it is good to compile frequently-used commands to process files in batches and then use them in the command line. For example, if you need to enter the ip address of the machine for ssh Login, you can create a batch processing file, such as ssh1, ssh2, ssh_wang, and ssh_liu. The actual ip address corresponding to ssh is used in this file, when there are fewer characters, the work will be faster, and you don't need to remember the long IP address every time. For example, you may be using a compilation environment. Each time it takes several steps to complete the compilation, you can also assemble the command set to be input into a bat file, in the future, you only need one step. Slowly, you may accumulate a set of your own bat commands. Although they are files one by one, they are actually simple command sets. You may forget the command name. You can write a simple list. bat command to print the command set of the bat directory to the screen.
List. the bat content is as follows, which is quite simple. The function is to print all bat file names and exe file names in the current directory and put them in the same directory as a series of bat files, at the same time, you can add the directory to the environment variable to enjoy the convenience it brings to you:
@ Echo off
: Echo "path = % ~ Dp0"
Dir/B "% ~ Dp0 *. bat "" % ~ Dp0 *. exe"

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.