Batch : Dynamic variable name (eval equivalent)

2019-06-26 05:17发布

问题:

I have a variable containing the name of an environnent variable. I would like to eval this value. For example:

:: TOTO_1_2 defined outside of batch file
set varName="TOTO_1_2"
echo %TOTO_1_2% :: Display env var
echo %%varName%% :: Broken

The idea is to pass the value of the env var pointed by varName to a command then.

Thank you

回答1:

if you want to evaluate a evaluated variable, you have to parse it twice:

There are different possibilities to do that. Here are three of them:

@echo off
SET TOTO_1_2=hello
set "varName=TOTO_1_2"
echo 0: %TOTO_1_2% 
call echo 1: %%%varName%%%

setlocal enabledelayedexpansion
for %%i in (%varname%) do echo 2: !%%i!
echo 3: !%varName%!