Using ENABLEDELAYEDEXPANSION
When us开发者_运维问答ing ENABLEDELAYEDEXPANSION in a batch script, do the variables that are created within it still exist after calling ENDLOCAL?
I understand, your question is basically about the SETLOCAL
command and its effects, regardless of the ENABLEDELAYEDEXPANSION
option (or any other one) used.
My short answer is: No, assuming the variables didn't exist prior to entering SETLOCAL
's scope.
My longer answer is as follows:
All the changes made to a variable within the scope of SETLOCAL
are discarded upon exiting the scope (i.e. upon reaching ENDLOCAL
). This includes:
defining a previously undefined variable:
@ECHO OFF <nul SET /P q=1. IF DEFINED ttt (ECHO defined) ELSE (ECHO undefined) SETLOCAL SET ttt= <nul SET /P q=2. IF DEFINED ttt (ECHO defined) ELSE (ECHO undefined) ENDLOCAL <nul SET /P q=3. IF DEFINED ttt (ECHO defined) ELSE (ECHO undefined)
This outputs:
1.undefined 2.defined 3.undefined
undefining a previously defined variable:
@ECHO OFF SET ttt=1 <nul SET /P q=1. IF DEFINED ttt (ECHO defined) ELSE (ECHO undefined) SETLOCAL SET ttt= <nul SET /P q=2. IF DEFINED ttt (ECHO defined) ELSE (ECHO undefined) ENDLOCAL <nul SET /P q=3. IF DEFINED ttt (ECHO defined) ELSE (ECHO undefined)
The output is:
1.defined 2.undefined 3.defined
changing a variable's value:
@ECHO OFF SET ttt=1 ECHO 1.ttt=%ttt% SETLOCAL SET ttt=2 ECHO 2.ttt=%ttt% ENDLOCAL ECHO 3.ttt=%ttt%
And this produces the following output:
1.ttt=1 2.ttt=2 3.ttt=1
As I said in the beginning, the above applies to SETLOCAL
regardless of whether you use it with additional options or not.
In conclusion I'd like to say that it is possible to save the result calculated within SETLOCAL
's scope, for use after ENDLOCAL
. Here's a little trick that makes it possible:
…
ENDLOCAL & SET var=%var%
…
At the time of parsing this line, the SETLOCAL
command is still in effect, so %var%
gets evaluated to the value you've stored into var
most lately. When the line is executed, the var
variable loses its value immediately after ENDLOCAL
, but the SET command already contains its value, just substituted, so var
receives it back, to everybody's satisfaction.
As per @Jeremy Murray's comment, you could also get access to the changed value after ENDLOCAL
if you included ENDLOCAL
and the command(s) reading the variable in a single block enclosed in parentheses:
…
(
ENDLOCAL
SET var=%var%
anything else
)
…
The effect would be the same because bracketed commands are both parsed and executed as a single unit: first they are all parsed, then they are all executed.
精彩评论