Home > Software design >  How to access a variable using content of another variable as name?
How to access a variable using content of another variable as name?

Time:12-12

I would access the value of a variable. The name of the variable I want to access is stored in another variable and/or passed by argument to the batch.

So, I want to achieve two things:

  1. calling batch with desired variable name as argument (and batch accessing the var directly):

    --> command line==batch.bat myVar

    {batch file:} echo (what is in variable myVar)

  2. calling batch with variable name that holds another varibale's name and output that other variable:

    Let's assume that the variable "var_name" exists and has the value "APPDATA"

    --> command line==batch.bat var_name

    {batch file==} echo (what is in variable APPDATA)

CodePudding user response:

Not 100% sure why you need this, but I am assuming you want something like:

@echo off & setlocal enabledelayedexpansion
set "var=appdata"

for %%i in (!%1!) do (
   echo original val from variable "%1" = "%%i"
   echo secondary val from variable "%%i" = "!%%i!"
)

Here, I have set a temp value for var to be appdata. When running scriptname.cmd var you'll get the relevant results for both variables var and its value appdata

  • Related