批次:从SETLOCAL EnableDelayedExpansion返回值 [英] Batch: Returning a value from a SETLOCAL EnableDelayedExpansion

查看:251
本文介绍了批次:从SETLOCAL EnableDelayedExpansion返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么因为预计今年code不工作:

  @ECHO关闭
SET S1 = HELLOSETLOCAL EnableDelayedExpansion
SET S2 =!S1!世界^^!
ECHO!S2!
ENDLOCAL&安培; SET S1 =!S2!ECHO%S1%
暂停

输出:

 世界,你好!
!S2!

期望的输出:

 世界,你好!
你好,世界!

感谢。


解决方案

据按预期工作。结果
延迟的扩张将在执行时扩展变量,而不是解析时间,因此除preT你行 ENDLOCAL&安培; SET S1 =!S2!的结果
ENDLOCAL 结果
但在 SET S1的部分=!S2!延迟扩展关闭,因此它不能再扩大了。

在你的情况,你可以使用
ENDLOCAL&安培; SET S1 = S2%%

由于感叹号S2是安全,作为延迟EXP。是关在执行的时刻。

但是,一个永远安全的返回是更复杂一点。结果
我们讨论它在 Dostips:返回跨ENDLOCAL疆

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.

解决方案

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

这篇关于批次:从SETLOCAL EnableDelayedExpansion返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆