variable sharing? Batch CMD

60 views Asked by At

I'm trying to set 2 variables in 3 categories, 6 variables total, copying out the categories three times seems like a poor option especially because my real code is much larger than this with almost 10 categories with 30 variables each.

First I ask which category to set variable (constant) and then asked to set the two variables in that category.

Which is fine, until I want to do something with the combined variable.

@echo off
cls

:start

cls
echo which variable do you want to set?
echo (1),(2),(3)
choice /c 123 /n
if ERRORLEVEL 3 goto :3
if ERRORLEVEL 2 goto :2
if ERRORLEVEL 1 goto :1

:1
set const=one
goto :wizard

:2
set const=two
goto :wizard

:3
set const=three
goto :wizard

:wizard
set /p %const%_varA= set %const% variableA: 
set /p %const%_varB= set %const% variableB: 

:: this line is the problem
echo %%const%_varA%
echo %%const%_varB%
:: 
echo.
pause
goto :filewrite

echo.

:filewrite
echo one varA %one_varA%
echo one varB %one_varB%
echo two varA %two_varA%
echo two varB %two_varB%
echo three varA %three_varA%
echo three varB %three_varB%

pause
goto :start
1

There are 1 answers

1
geisterfurz007 On BEST ANSWER

I have played around a bit and the problem you have is the fact that in batch-files the way to escape a % is another one. So your code will eventually look like echo %const%_varA% and as %var_A% is empty/does not exist, the only thing you should be getting is %const as output.

Luckily there is a way to bring another character into the game to prevent this from happening. Adding setlocal EnableDelayedExpansion under the first line will make variables accessable using exclamation marks. This is usually used to access variables in closed sets of parenthesis but comes in handy for this one:

@echo off
setlocal EnableDelayedExpansion
set const=three
set %const%_varA=foo
echo Without exclamationmarks: %%const%_varA%
echo With exclamationmarks   : !%const%_varA!
pause

Is a tiny example that demonstrates the problem.
The upper line is what you currently have and not working. The lower one however uses above explaned delayed expansion.
Meaning: First (%) the value of %const% is calculated, changing the line to echo [...] !three_varA! and after (!) comes the whole thing!

Feel free to ask questions :)