Reputation: 123
The code below is related to batch files (command prompt). My problem is the part of the code that says current value is %~1
doesn't actually display the value of %~1
(I would like it to say string01 or string02) am not too sure how to do this. I have looked around but cannot wrap my head around this simple problem.
@echo off
goto :MainFunction
:Func01
echo.
echo Running Func01
echo Variable %~1 current value is %~1
echo.
echo Set new value for Variable %~1:
set /p %~1=
goto :eof
:MainFunction
echo This is the main function!
set Var01=string01
set var02=string02
echo Var01 is equal to %Var01%
echo Var02 is equal to %Var02%
call :Func01 Var01
call :Func01 Var02
echo Var01 is now equal to %Var01%
echo Var02 is now equal to %Var02%
goto :eof
Upvotes: 3
Views: 655
Reputation: 49127
Another method is using command CALL to get a double parsing of a command line as shown below:
@echo off
goto :MainFunction
:Func01
echo/
echo Running Func01
call echo Variable %~1 current value is %%%~1%%
echo/
set /P "%~1=Set new value for Variable %~1: "
goto :EOF
:MainFunction
echo This is the main function!
set "Var01=string01"
set "var02=string02"
echo Var01 is equal to %Var01%
echo Var02 is equal to %Var02%
call :Func01 Var01
call :Func01 Var02
echo Var01 is now equal to %Var01%
echo Var02 is now equal to %Var02%
goto :EOF
The command line
call echo Variable %~1 current value is %%%~1%%
is first modified before running CALL by Windows command interpreter for example on first execution of subroutine Func01
to
call echo Variable Var01 current value is %Var01%
On parsing this command line a second time on running CALL the command line changes to:
echo Variable Var01 current value is string01
The character %
must be escaped with one more %
to be interpreted as literal character in a batch file which is the reason for the strange looking syntax %%%~1%%
.
And take a look on DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/ for the explanation on using echo/
instead of echo.
to output an empty line.
Upvotes: 2
Reputation: 56188
You want to get both the variable name and the value in a single parameter?
In the line echo Variable %~1 current value is %~1
, the second %~1
has to evaluated. Sou need another layer of parsing. The "usual" way to do so, is to use delayed expansion:
@echo off
setlocal enabledelayedexpansion
goto :MainFunction
:Func01
echo.
echo Running Func01
echo Variable %~1 current value is !%~1!
echo.
echo Set new value for Variable %~1:
set /p %~1=
goto :eof
:MainFunction
echo This is the main function!
set Var01=string01
set var02=string02
echo Var01 is equal to %Var01%
echo Var02 is equal to %Var02%
call :Func01 Var01
call :Func01 Var02
echo Var01 is now equal to %Var01%
echo Var02 is now equal to %Var02%
goto :eof
Upvotes: 3