Batch: Returning a value from a SETLOCAL EnableDelayedExpansion

你说的曾经没有我的故事 提交于 2019-12-01 04:38:39

问题


I wonder why this code does not work as expected:

@ECHO off
SET S1=HELLO

SETLOCAL EnableDelayedExpansion
SET S2=!S1! WORLD^^!
ECHO !S2!
ENDLOCAL & SET S1=!S2!

ECHO %S1%
PAUSE

Output:

HELLO WORLD!
!S2!

Expected output:

HELLO WORLD!
HELLO WORLD!

Thanks.


回答1:


It works as expected.
The delayed expansion will expand variables at execution time, not parse time, so it interpret your line ENDLOCAL & SET S1=!S2! as
endlocal
But at the part of SET S1=!S2! the delayed expansion is off so it can't be expanded anymore.

In your case you could use ENDLOCAL & SET S1=%S2%

As the exclamation mark is S2 is "safe", as the delayed exp. is off at the moment of execution.

But an always secure returning is a bit more complicated.
We discussed it at Dostips: Return ANY string across ENDLOCAL boundry



来源:https://stackoverflow.com/questions/9408953/batch-returning-a-value-from-a-setlocal-enabledelayedexpansion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!