windows batch command nested variable

落爺英雄遲暮 提交于 2019-12-12 04:54:21

问题


I have a requirement to use nested variables for creating a folder based on a environment variables.

Assume I have variables listed below:

%ABC_ASIA_LOCATION% 
%ABC_EUROPE_LOCATION%
%ABC_US_LOCATION%

and I want to pass the country as variable like %ABC_%COUNTRY%_LOCATION%.

How do I achieve this in Windows utilizing batch scripting?


回答1:


you have to enclose each variable into %:

set "ABC=ABC"
set "COUNTRY=EUROPE
set "LOCATION=MUNICH
echo %ABC%_%COUNTRY%_%LOCATION%

Result: ABC_EUROPE_MUNICH

Or if you just want Country as a variable, keeping the rest fixed:

echo ABC_%COUNTRY%_LOCATION

Result: ABC_EUROPE_LOCATION

or if you want the whole thing to be a variable (a variable name containing another variable), you have to use delayed expansion:

setlocal enabledelayedexpansion
set country=EUROPE
set "ABC_EUROPE_LOCATION=a town in southern Germany"
echo !ABC_%country%_LOCATION!

which gives you: a town in southern Germany

Note: setlocal has no effect outside of batchfiles, so delayed expansion works only:
- in batchfiles
- when the command prompt was started with delayed expansion enabled (cmd /v:on) (by default, the command prompt runs with delayed expansion disabled)



来源:https://stackoverflow.com/questions/46067287/windows-batch-command-nested-variable

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