いくつかの編集が必要でしたが、最終的に真の防弾オプション (方法 5) を思いつきました。
方法 5 で、var3 が次を含む変数名に置き換えられた場合、"
いくつかの引用符をエスケープする必要があります。しかし、あなたが変数名に引用符を入れるのに十分なほど洗練されているなら、あなたはすでにそれを行う方法を知っています:-)
@echo off
setlocal
set var1=5
set var2=var1
set var3=var2
::method 1 - Without using delayed expansion. (this is relatively slow and unsafe)
:: the initial expansion uses 1 % and no CALL
:: the 2nd expansion uses CALL and 2 %%
:: the 3rd expansion uses CALL and 4 %%%%
:: each additional expansion would require another CALL and doubled percents
call call set "test=%%%%%%%var3%%%%%%%
if "%test%"=="5" echo Method 1 works: Value of "unknown var"=%test%
::The remaining methods use delayed expansion. They are safer and faster.
setlocal enableDelayedExpansion
::method 2 - Using normal and delayed expansion and a temp variable.
:: Almost always works, but can fail in rare cases where variable
:: name contains "
set "test=!%var3%!"
if "!%test%!"=="5" echo Method 2 works: Value of "unknown var"=!%test%!
::method 3 - Using normal and delayed expansion without using any temp variable.
:: This works for sensible variable names, but fails if name contains
:: * or ?. Also can fail if variable name contains "
for %%A in ("!%var3%!") do if "!%%~A!"=="5" echo Method 3 works: Value of "unknown var"=!%%~A!
::method 4 - Using normal and delayed expansion without using any temp variable.
:: This almost always works, but can fail in rare cases where variable
:: name contains "
for /f "eol==delims=" %%A in ("!%var3%!") do if "!%%A!"=="5" echo Method 4 works: Value of "unknown var"=!%%A!
::method 5 - Using delayed expansion without using any temp variable.
:: This always works!
for /f "eol==delims=" %%A in ("!var3!") do for /f "eol==delims=" %%B in ("!%%A!") do if "!%%B!"=="5" echo Method 5 works: Value of "unknown var"=!%%B!