0

I have the name of an variable saved as a string (it will be read in from a CONFIG file). I would like to evaluate this environment variable, to print its value to the console for example. I am unsure of how to do this.

My current script:

@echo off

set env_var=VIVADO_BAT_PATH_2018_3

set str=set vivado_bat_path=%env_var%
%str%
echo "bat path:  %vivado_bat_path%"

set str=set vivado_bat_path=%%env_var%%
%str%
echo "bat path:  %vivado_bat_path%"

Its current output:

"bat path:  VIVADO_BAT_PATH_2018_3"
"bat path:  %env_var%"

Desired Output:

"bat path:  C:/Xilinx/Vivado/2018.3/bin/vivado.bat" (or whatever value the env var is set to)

I know that I could get the desired output with echo %VIVADO_BAT_PATH_2018_3% but I am reading in VIVADO_BAT_PATH_2018_3 as a variable, so how would I go about doing this?

perry_the_python
  • 385
  • 5
  • 14

2 Answers2

1
@ECHO OFF
SETLOCAL
set "VIVADO_BAT_PATH_2018_3=I Want This String"
set env_var=VIVADO_BAT_PATH_2018_3

set str=set vivado_bat_path=%env_var%
%str%
echo "bat path:  %vivado_bat_path%"

set str=set vivado_bat_path=%%env_var%%
%str%
echo "bat path:  %vivado_bat_path%"

set "bingo=Not Found"
for /f "tokens=1*delims==" %%a in ('set %env_var% 2^>nul') do if /i "%%a"=="%env_var%" set "bingo=%%b"
echo I found "%bingo%"

GOTO :EOF

This should expand your variable, in addition to your code.

I forced the value of VIVADO_BAT_PATH_2018_3 since it does not exist on my system.

The if /i ensures that should an environment variable named VIVADO_BAT_PATH_2018_3_old exist for instance, then only the variable exactly named VIVADO_BAT_PATH_2018_3 is reported.

The 2^>nul suppresses error messages should VIVADO_BAT_PATH_2018_3 not exist. The ^ escapes >, telling batch that the > is part of the set command, not the for command. bingo is set before the for to ensure that any existing value for bingo is not mistaken for the desired value should bingo be already set when the batch runs.

Magoo
  • 77,302
  • 8
  • 62
  • 84
1

To get the value of a value of a variable, the "usual" way is to use delayed expansion.
But you can also force a second parsing ("expand an expanded variable"). You can do that with the call command (which executes the following command within a second separate process). To pass a literal % to the second process, escape it with another %, which explains the strange triple%.

@echo off
setlocal enabledelayedexpansion

set "string=varname"
set "varname=some text"

echo with delayed expansion:    %string% = !%string%!
call echo without delayed expansion: %string% = %%%string%%%
Stephan
  • 53,940
  • 10
  • 58
  • 91