Search code examples
batch-filevariablesconcatenation

.bat file - How can I return the value of a variable whose name depends on another variable concatenated with a string in a batch file?


In my main batch file I ask the user for an input (limited to certain strings) and store it as a variable I then need to append a string to that variable to create the name of another variable and return the value of this variable which is stored in another file.

Fruity example of what I'm trying to do for simplicity:

In my config file I would have something like this:

set banana_colour=yellow
set orange_colour=orange
set strawberry_colour=red
etc...

Then in my main file I would have

set /p fruit="Please input a fruit: "

I would then like to be able to return the value of a variable in the config file by concatenating the user input with a string (in this example _colour). So if the user entered banana, I would echo the value of the variable with the name banana_colour which in this case would be yellow.

I tried to set a new variable which was the concatenation of the input and the string and then echo the variable of that string. For example:

set colour=%fruit%_colour
echo %colour%

But of course, that does not return the value of the variable with that name it just returns the name: banana_colour instead of yellow.


Solution

  • a variable name containing a variable is a common problem. Here are two possible solutions:

    @echo off
    setlocal enabledelayedexpansion
    
    set banana_colour=yellow
    set orange_colour=orange
    set strawberry_colour=red
    
    set /p fruit="Please input a fruit: "
    echo %fruit% is !%fruit%_colour! (delayed expansion)
    call echo %fruit% is %%%fruit%_colour%% (without delayed expansion)
    if "!%fruit%_colour!" == "" echo I don't know the colour of %fruit%.
    

    Details