Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What the dos environment variable delay extension enabledelayedexpansion looks like

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

In this issue, the editor will bring you about how the dos environment variable delay extension enabledelayedexpansion is. The article is rich in content and analyzes and describes it from a professional point of view. I hope you can get something after reading this article.

First, what is deferred environment variable extension?

Delay variable is the full name of "delay environment variable extension", to understand this thing, we also need to understand what variable extension is!

When CMD interprets our command, it will first read a complete command, and then perform some matching operations on the command format, depending on what you enter.

Whether the command format meets its requirements. If we are going to reference some variables in a command, how can we get CMD to recognize when interpreting our command

What about this variable? At this point, we can add a% sign to both sides of the variable name, such as% name%. When CMD is reading our entire command for format matching

Later, you will find that if a% sign is added to the character name, it will not be treated as an ordinary character, but as a variable called name.

CMD then finds the value corresponding to the variable name, replaces the variable name (name) with that value, and returns a null value if no value exists in the variable name. And then put this

Execution of commands that are replaced and matched! The process of replacing the value is called variable extension, which, to put it bluntly, is to replace the name of the variable with its value.

Execute! That is, the process of batch processing how to identify a variable. (note: this is only the meaning of the extension of variables, not delaying the extension of environment variables, but to understand the extension

Late environment variable extension, we must first understand what is variable extension), that is, the process of batch processing how to identify a variable.

Example 1

@ echo offset var=testecho% var%pause

After reading the command echo% var%, CMD will match. It will immediately find that there is a% sign on both sides of the var character, and CMD will treat it as a

To see if the var variable name has a value, and if so, replace the variable name var with this value. Here our var is in the previous command set.

In var=test, var is assigned test, so CMD will replace the variable name% var% with test, and the result will be echo test. These steps

All of a sudden, it is the step of CMD to match. After matching, he executes the statement echo test, and then we will echo a test in our CMD.

What is environment variable extension? see, what is deferred environment variable extension?

When we understand the environment variable extension, we know that when CMD interprets a command, it will first read a complete command, and then perform a match operation.

It replaces the variable in the command with the value of the variable, and then executes the replaced command. The problem is "one complete command", in BAT, IF

Commands like FOR can be executed in parentheses to nest some commands inside. In this case, for a command that can be added with an extension to embed other commands, his end

The whole format is for% I in (....) Such a whole. At this point, if we embed some commands to set the value of the variable in parentheses, it will appear.

Problem!

Example 2

@ echo offfor / l% I in (1meme 1je 5) do (set var=%%i echo% var%) pause

An error message of 5 blank lines will be displayed after execution! Why? According to the knowledge we mentioned above.

Through these two examples, you should have understood that if only environment variables extend this process, if we execute in commands that can be nested.

The assignment operation will cause our BAT to have the problem of assigning values to variables. Then the concept of "delaying the extension of environment variables" is put forward at this time.

In batch processing, we can use the setloacl enabledelayedexpansion command to enable "deferred environment variable extension" when we enable

After delaying the extension of environment variables, when CMD interprets commands with nested formats, he executes the nested commands one by one, and then enters

Line matching operation, so that our assignment operation will be completed. And when "deferred environment variable extension" is enabled, CMD will use! To determine whether this is a variable or not

. If you do not enable the variable before using the format of% name%, then use! name! This format is judged, this symbol we need to pay attention to!

Example 3

@ echo offsetlocal enabledelayedexpansionset var=1for / l% I in (1meme 1je 5) do (set / a var=% I echo! var!) pause

In this way, we should understand what is the extension of deferred environment variables. Let me give you another example.

Example 4

@ echo offset var=test & echo% test%pause

This command is placed on one line, indicating that it is a complete command. If you do not enable "delay environment variable extension", the above assignment error will occur! Change it to this.

OK:

@ echo offsetlocal enabledelayedexpansionset var=test & echo! varicipause

Second, detailed explanation of batch variable delay

For delay extension of environment variables, use set /? You can see some of the instructions, but in view of its poor translation level, it is recommended that before checking it, the first

First chcp 437 switch to English to view the original English instructions. Given that the article is very detailed, and there are several code examples, it should not be difficult to understand. Here only

To add a little bit.

In many visible official documents, a pair of percent signs is used to close environment variables to complete the replacement of their values called "expansion"

) ", this is actually a first-party concept, which is called from the point of view of the command interpreter, and from the point of view of our users, we can use it

Think of it as a Reference, a Call, or a Get.

The behavior of the command interpreter to extend the environment variable is roughly as follows: first read a complete statement from the command line, after some prior preprocessing

Before the command is interpreted and executed, the string closed with the percent sign will be matched if a ring matching the string is found in the ambient space

Context variable, replace the original string and the percent sign itself with its value, and if there is no match, replace it with an empty string, which is the value of the environment variable

"extension", which still belongs to the command line preprocessing category.

A "complete statement" is interpreted in NT's command interpreter CMD as "for if else" and other statements containing statement blocks and the use of "& |

"and other concatenated compound statements.

Therefore, when CMD reads the for statement, all statements closed with a pair of circular commas will be read together and the necessary preprocessing work will be completed, where

This includes the extension of environment variables, so before all statements in for are executed, all environment variables have been replaced with the values set before for

It becomes a string constant instead of a variable. No matter how you modify those environment variables in for, what is really affected is the null environment variable.

, not inside the for statement.

In order to be able to perceive the dynamic changes of environment variables within the for statement, CMD has designed a delayed environment variable extension feature, that is, when CMD reads

After a complete statement, it does not immediately perform the extension behavior of the variable, but extends before a single statement is executed, that is to say

This extension behavior has been "delayed".

The delay environment variable extension feature is off by default in CMD, and there are two ways to turn it on: one is CMD / v:off.

CMD / v:on--namejm Note), which opens a new command line shell, and the extension feature is always in effect until you exit it using exit

Commonly used in command-line environments; second, setlocal EnableDelayedExpansion, which limits the modification of environment variables to local space, in

After endlocal, the extension feature and previous modifications to environment variables disappear together and are often used in batch statements.

The above is a post written by willsort that is difficult for beginners to understand. But it doesn't matter. Let's first analyze an example, which is also quoted from willsort Lao.

Big.

This example enables variable delay, which is a correct example!

Example 1

@ echo off & setlocal EnableDelayedExpansionfor / f "tokens=* delims="% I in ("Hello world.") Do (set nude%% I set nlug ld.roomt! Set nympho w = S! Set does not need to pay attention to it. Echo! n!) Pause

Saving the above code as .bat double-click to execute will display the "Will Sort" string. The meaning of each statement is explained below:

1.@echo off & setlocal EnableDelayedExpansion

Turn off command echo and enable variable delay

2.for / f "tokens=* delims="% I in ("Hello world.") Do ()

For the use of the for command and its parameters, please search for relevant words in the forum. Limited to the question of space, we will not discuss it here. If you don't understand what it means at this time,

Think of it as its function of putting the string "Hello world." Assign a value to% I. Of course, this is only a stopgap measure. You must learn for in the future.

Use of!

3.set% I

We all know that the value of% I (i.e. Hello world.) is assigned to the variable n.

4.set nymphalism ld.bott!

Here we will talk about the function of replacing characters in set. This statement means that you first get the value of the variable n (where the value of n is "Hello world."), and then

Replace the character "t" with the character "ld.", and then assign the replaced result to the variable n again (where the value of n becomes "Hello wort"). As for

The format of set replacement characters. You can type "set/?" in CMD. Find "% PATH:str1=str2%" with instructions

5.set nympho w = S!

The meaning is the same as the previous sentence, but the content to be replaced is different from that to be replaced. It replaces "o w" with "S" (notice that there is a space before S and w), and its

The real willsort boss is trying to prove that set substitution characters support periods and spaces (there is a. After the fourth sentence "ld"). The value of n at this time is "Hell Sort"

6.set does not need to pay attention to it.

Needless to say, after executing this sentence, the value of n is "Will Sort".

7.echo! n!

Display the value of the variable n

It is important to note that once variable delay is enabled, use it! The sign encloses the variable, not the% sign.

All right, now that we've finished the meaning of each sentence, let's talk about the variable delay that this post is really going to discuss.

Here I would like to quote the explanation of the boss of Will Sort: when CMD reads the for statement, all the statements closed with a pair of parentheses will be read together and complete.

The necessary preprocessing work, which includes the extension of environment variables, so that all environment variables have been replaced before all statements in for are executed

Change to the value previously set by for, so that it becomes a string constant instead of a variable.

In order to be able to perceive the dynamic changes of environment variables within the for statement, CMD has designed a delayed environment variable extension feature, that is, when CMD reads

After a complete statement, it does not immediately perform the extension behavior of the variable, but extends before a single statement is executed, that is to say, this

The extension behavior has been "delayed".

In general, without enabling variable latency, all variables in parentheses (that is, in do) have been called before the for statement is executed

Replace with the value assigned to the variable by other commands before the for statement. It doesn't matter if you don't understand this sentence. Let's look at another example, and you'll understand.

Example 2

@ echo offfor / f "tokens=* delims="% I in ("Hello world.") Do (set n=%%iset n=%n:ld.=t%set n=%n:o w = S% set nasty% n set Hefei% echo% n%) Pause

This is similar to the previous example, but all! The number is changed to the% number, which is a wrong example. Because it does not enable variable latency, nor is it used!

Sign encloses the variables. We see that the result of its execution is that "ECHO is off".

What causes it? The reason is that without enabling variable latency, all variables in parentheses (that is, in do) are executed before the for statement

Has been replaced with the value assigned to the variable by other commands before the for statement

It means the following sentences in this example

Set n=%%iset n=%n:ld.=t%set n=%n:o w = S%set n=%n:He=Wi%echo% n%

The first sentence executes normally and achieves its purpose, because it simply assigns the value of% I to the variable n, so there is no problem. A few other sentences belong to

This is the case: long before the for statement is executed, CMD impatiently performs the substitution behavior of all the variables n in these sentences together, replacing it with for.

The value set by other commands for n, so that n becomes a constant. But in this case, there is only @ echo off before the for statement, and there are no other commands

Any assignment has been done to n, so before for, the value of the variable n was null.

That is to say, the variable n in the sentence "set n% n" is read by CMD (note that it is read rather than executed) after the entire for statement has been read (not yet in turn).

To set to perform its own task), it is immediately replaced with a null value, which has nothing in it, so there is no substitute for another word.

How do you replace it if there is nothing? ). In the end, when you execute the set nforth% nvvl.% statement, it just takes a null value and assigns the variable n

It's a null value. The same principle applies to other sentences.

So, in the end, the variable n is still null when echo% n%, and the echo command has nothing to show except that "ECHO is off"

"this sentence explains your state.

Through the illustration of this example, I believe we already know the role of variable delay! Let's go back to example 1.

After variable delay is enabled, after execution

Set has not been installed since the beginning of the week.

Before these statements, the variable n in them is not immediately replaced by CMD (after enabling delay, CMD becomes patient ^ _ ^), but if it is not replaced, then n

It's still a variable, not a constant. Wait until the execution of the set ninstrumentnRu ld.Secrett! Wait for these sentences before the variable n is replaced. So that every set command can perceive variables

Any change in n to make the correct replacement behavior. This is the variable delay!

Don't think that only for should use variable delay. The following example also requires

Example 3, this is a wrong example

@ echo offset mm=girl&echo% mm%pause

"ECHO is off" is still displayed after execution.

The reason is that latency is not enabled, and there are no other commands to assign mm before the set mm=girl&echo% mm% statement. When CMD executes set at this time

Before the mm=girl&echo% mm% statement, the value of the variable mm was replaced impatiently, and because there was no previous assignment to mm, mm was replaced with null

Value, becomes a constant. When the echo command is executed, it is actually an immutable constant for echo, which in this case is null.

Some people may ask, didn't echo assign values to mm before?

This is related to the steps of CMD to explain the command. You can refer to the willsort post at the beginning of this post.

In general, if variable delay is not enabled, in this case, echo will ignore and will not know whether there is a

It commands to assign a value to mm. It will only get the contents of the variables it wants to display from the statement above set mm=girl&echo% mm%, that is, the

The echo command displays the value of mm as set by one or more previous lines of command.

If you do this, you will understand:

@ echo offset mm=boyset mm=girl&echo% mm%pause

Just see what results are displayed.

This is the right way to write example 3:

@ echo off&setlocal EnableDelayedExpansionset mm=girl&echo! mm roompause

When variable delay is turned on, the behavior of variable extension (replacement) is postponed until the execution of the echo command, when echo can sense the command in front of it (set in this example)

What "bad things" have been done to the variable mm to make a correct judgment and execute it?

Third, batch delay variables (popular interpretation)

Variable delay setlocal EnableDelayedExpansion

A problem that makes most beginners have a headache, although there are many online tutorials, but most of them do not understand, there are too many professional terms.

Take this tutorial by willsort of the cn-dos Alliance as an example. (personally, I think it is very authoritative and professional.)

But it may be because of the major, so do not understand, because the study of cmd batch processing is not necessarily a computer major. This damn thing is really not very good.

Understand, I also touch, crawl and roll for a long time, sum up a little bit of experience, and now explain it in a popular way, hoping to give some help to beginners. Old birds laugh.

Yes, if there is anything wrong, you are welcome to point it out.

Let's get back to the point

When do you need a delay variable, and how to reference a delay variable? I think this is what most novices are eager to know.

After reading the following patiently, I think it should be helpful to you.

To understand the delay variable, you first need to understand what is a "compound statement" as if there is another "professional" noun. Don't worry, this is super easy to understand. The so-called

"compound statement" refers to all the commands in a pair of (). Like behind for's do.

Such as:

For / f "delims=" I in (a.txt) do (set var=%%i echo I set num=%%i)

Here do the following three commands, in a pair of (), this is called "compound statement", of course, not only for but also if and so on.

Such as:

If "% var%" = = "abc" (echo ok set lis=123)

Anyway, all the commands in () are called "compound statements".

In addition: this is also a compound statement set abc=123&echo% abc% yes, through pipe commands & connected commands, is also a compound statement.

OK, now that we understand the compound statement, let's start talking about delay variables, that is, we should only use delay variables in compound statements.

Let's not understand what is meant by "expansion of variables". It's too professional. I still don't understand it.

We just need to know when we need to use deferred variables and how to extract the variables we need correctly, which is our goal.

When dealing with a compound statement, cmd will refer to the value of the variable as the value of the variable before the compound statement if the variable is used in the compound statement.

. If the variable has not been assigned before, it is treated as null.

Example 1

@ echo offfor / l% I in (1 1 10) do (set var=%%i echo% var%) Pause

Run the above code, what does it show? Shows that 10 echo are off. Logically, the values of var should be 1,2,3.10 respectively.

Yeah!

This is because the delay variable is not enabled, and cmd refers to the value of var as the value before the compound statement.

In this case, the var was not defined before the compound statement, so the value of var is empty, so 10 echo are shown to be off.

Example 2

@ echo offset var=abcfor / l% I in (1 1 10) do (set var=%%i echo% var%) Pause

Run the above code, what will be displayed, you should know, right?

Example 3

Echo offset var=abcfor / l I in (1 15) do (set var%%i=%%i echo var%) echo var1% var2% var3% var4% var5%pause

After running the above code, all the values assigned in the compound statement are displayed. What does that mean?

It shows that in the compound statement, it is not that there is no value assigned to the variable, but if you do not turn on the delay variable, you will not be able to extract it in the compound statement.

It can not be extracted until the compound statement has been run.

Variable representation: 1,% var% 2,! var!

The first method of representation, as we all know, is to refer to delayed variables.

When the delay variable is turned on, it can be expressed either way outside the compound statement. But if you want to quote a compound in a compound statement

The second method should be used to get the variables in real time. Look at the example.

Example 4

Echo offsetlocal EnableDelayedExpansionset var=abcfor / l% I in (1 1 10) do (set var=%%i echo% var% echo! var!) Pause

Note: there are two echo in the example, one is to display% var% and the other is to display! var!

The result is clear that the result displayed by% var% is the value of the variable var before the compound statement, and! var! What is displayed is the value immediately obtained in the compound statement.

Example 5

Echo offsetlocal EnableDelayedExpansionfor / l I in (1 15) do (set var%%i=%%i) echo% var1%% var2%% var3%% var4%% var5%echo! var1! var2! var3! var4! var5roompause

What does this example illustrate? there is no need to explain it any more, right?

Indicates that variables can be represented in both ways when deferred variables are turned on and outside the compound statement. That's it. The above explanation, end

It is all out of personal understanding, but also for the convenience of non-professionals to understand, to explain that there must be mistakes, just like when learning English, in order to facilitate memory, use Chinese

The pronunciation of the word is the same as an explanation. Ha ha, it is a kind of "partial door". Novices must not regard what has been said above as "truth", otherwise it will become "true".

It's a mistake.

Fourth, when to use the delay variable? How to use it?

When to use delay variables? How to use it? These are always the places that confuse beginners, so what's it like? Then take a look at the following example

We will guide you step by step.

Example 1

@ echo offset / a num=0for / l% I in (1 1 3) do (Rem = = set / a num= 1 Rem means to add 1 Rem = = echo% num%) pause > nul each time the value of the variable num

First guess, what is the result after running? Do you think it will show: 1, 2, 3? I think most people would think so. You are going to use

Save the code as a batch file, run it, and see the results.

You will see that the result shown is not the expected 1, 2, 3, but 0, 000. Why is this?

The original reason is that when batch processing variables in for or if statements, it has to preprocess the variables enclosed in%%, first.

Replace with the variable before the statement (as in the code above, the% num% in the for statement has long been replaced with the pre-statement value: 0), so when the for statement runs

Although 1 has been added to the variable, the value remains the same (because the% num% in echo% num% has already been replaced with: 0).

So, what should I do to achieve real-time changes in variables in (for or if) statements (as here, I'm going to show 1 / 2 / 3)? Then get up.

With the delay variable, first declare: setlocal enabledelayedexpansion in the batch, and then change the statement: echo% num% to! num!

Is to change "%" to "!"), so that you can achieve the effect, demonstrate the code:

Example 2

@ echo off Rem''/ the following states that the delay variable / setlocal enabledelayedexpansionset / a num=0for / l% I in (1 13) do (Rem = = set / a num= 1 Rem variable num is added each time by 1 Rem = = Rem'/ the following variables can no longer be enclosed by "%" Instead, use "!" / echo! num!) pause > nul

Summarize:

1. Why use delay variables?

Let variables in if statements and for statements change in real time

2. When to use delay variable?

It is generally used in for statements and if statements

3. How to use delay variable?

First declare the start delay variable in the batch: setlocal enabledelayedexpansion

Then use the variables in the for statement and the if statement with two "!" Just wrap it up.

4. In fact, you can also use variable delay when using variable nesting variables.

Example 3

@ echo offset a=1set b1=10echo% b%a%%pause

Execution display, get% b1%

In fact, what I want to get is the value given to b1, that is, 10, so how do I achieve it? Modify the above example as follows

Example 4

@ echo offset a=1&set b1century 10 call echo% b%a%%%pause > nul

Call here is actually reorganizing and expanding the command line, first expanding% a% in%% b% a%, making% a% into a value of 1, and then using cal to expand% b1%

.

It can also be achieved with variable delay, as follows:

Example 5

@ echo offset / an axiom 1 direction b1century 10Setlocal EnableDelayedExpansionechoechovision pause% a%!...

The use of call here is actually a shortcut to variable delay, which is generally used in the loop body of for.

The comma here in call,%%b%a%%% is actually a delimiter, and like spaces, there are many delimiters available, such as echoechochrome separb% a% in the example above!

Of course, not all orders can be used in this way, depending on the situation.

Example 6

@ echo off&setlocal enabledelayedexpansionset a=1000set b=ddset a%b%=9000set caterpillar% b%! Echo c%pause

Execute it and see what will be displayed. Why is that? I believe you can analyze it through example 4 and example 5, right?

This is how the delay extension enabledelayedexpansion of the dos environment variable shared by the editor is like. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report