DOS batch: SET variable and ECHO it within (…) block

跟風遠走 提交于 2021-02-06 09:14:48

问题


I had a problem with set not working in a batch file; it took a while to distil the problem; at first I thought it was to do with subroutine calls...

The script

@echo off
setlocal
set a=aaa
echo a = "%a%"
(
set b=bbb
echo b = "%b%"
)

produces the output

a = "aaa"
b = ""

whereas I'd expect

a = "aaa"
b = "bbb"

Why is this please? Is it a bug in DOS? Perhaps there's something about the (...) command grouping syntax that I'm unaware of.

Thanks.


回答1:


User delayed expansion and ! instead of %

@echo off
setlocal enableextensions enabledelayedexpansion
set a=aaa
echo a = "%a%"
(
set b=bbb
echo b = "!b!"
)



回答2:


What's happening is that the batch interpreter as treating everything in between the brackets a single line. This means it's doing variable replacement on everything betweeen the brackets before any of the commands are run.

So:

(
set b=bbb
echo b = "%b%"
)

Becomes:

(
set b=bbb
echo b = ""
)

The variable b is being set but obviously isn't set before you run the SET command.




回答3:


You need delayed expansion to be on, or the batch interpreter will interpolate all variables at parsing time, instead of run time.

setlocal enableextensions enabledelayedexpansion

See this question for an example and some great explanation of it.



来源:https://stackoverflow.com/questions/1687233/dos-batch-set-variable-and-echo-it-within-block

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