Home > front end >  Is it possible to use a variable to change text inside a variable in batch?
Is it possible to use a variable to change text inside a variable in batch?

Time:09-12

I'm trying to make a variable that I can call upon to do set /p variable=enter: However I would also like to be able to change the variable to make it multi-purpose, here is what I have so far:

set enter=set /p %secvar%=Enter:

:new
set secvar=name
cls
echo what is your name
%enter%
goto name

This doesn't work and I don't understand what I'm doing wrong, how do I make this work or is what I'm doing naïve?

CodePudding user response:

How about this?

@echo off
setlocal
call :enter #one "Your value for '#one' ? "
call :enter #two "Your value for '#two' ? " "default for #2"
call :enter #three "Your value for '#three' ? " defaultfor#3
call :enter #four "" "default for #4"
call :enter #five "" defaultfor#5
call :enter #six "Your value for '#six' ? "
call :enter #seven 
call :enter #eight "" defaultfor#8
call :enter #nine "" "default for #9"
set #
goto :eof

:enter
set "%1=%~3"
if "%~2"=="" (set /p "%1=Please enter value for %1 ? "
 ) else (set /p "%1=%~2")
goto :eof

The routine :enter accepts 1 to 3 parameters. The first is a variable-name to set, the second is optional - the prompt message. The third parameter is also optional, specifying the value to use if the response is just Enter.

The second and third parameters may be quoted strings or a single string of characters. The second parameter must be "" for no prompt but set a default value.

Run the demonstration and reply 1..9 in sequence. This will show the values assigned. Run again but just reply Enter to the prompt; the result will be that those variables with a default value will be set to that default, those without will be "set" to nothing (ie. will be deleted from the environment if they existed)

  • Related