Using the Windows XP CMD command-line I can expand a variable twice as follows:
set AAA=BBB
set BBB=CCC
for /F "usebackq tokens=*" %i in (`echo %%AAA%%`) do echo %i
will echo CCC. I.e. AAA has been expanded to the string BBB, and then the variable BBB has been expanded to CCC.
This doesn’t work from inside a batch script (i.e. a .cmd file). Changing the %%AAA%% to either %%%AAA%%% or %%%%AAA%%%% doesn’t work either.
Any idea how i can achieve this from within a script, namely to take expand the variable AAA to the string CCC?
Late Edit
The answers posted work for my reduced example however the non-tortuous answer doesn’t work for the real case. Here’s an extended example (which doesn’t work), which illustrates what I was actually trying to do:
setlocal enabledelayedexpansion
set LIST=BBB CCC DDD
set BBB=111
set CCC=222
set DDD=333
for %%i in (%LIST%) do (
for /F %%a in ('echo %%%i%') do echo !%%a!
)
I would like to see
111
222
333
output.
Thinking in terms of a less tortuous solution, this, too, produces the
CCCyou desire.edit:
to dissect this answer:
setlocal enabledelayedexpansion– this will allow for any environment variable setting during your bat to be used as modified during the process of yourforloop.set AAA=BBB,set BBB=CCC– your data populationsetstatementsfor /F %%a in ('echo %AAA%') do echo !%%a!– This tells the processor to loop, albeit only once, and take out the first token that is returned (default delimiter of space and tab apply) from the running of the command in the parens and put it in the var %%a (outside of a batch, a single % will do). If you specify that var as %%a, you need to use %%a in yourdoblock. Likewise, if you specify %%i, use %%i in yourdoblock. Note that to get your environment variable to be resolved within thedoblock of theforloop, you need surround it in!‘s. (you don’t need to in theinblock, as I originally posted – I have made that change in my edit).edit:
You were very close with your updated example. Try it like this:
The difference between your update and this is that you were trying to echo the environment variable in the
inset within ('echo %%%i%'), but without the!‘s for the delayed expansion of set variables. Were you to usein ('echo !%%i!'), you would see yourBBB,CCC, andDDDvariables resolved, but then thedoblock of your inner loop wouldnt have anything to resolve – you dont have any111environment variables. With that in mind, you could simplify your loop with the following: