0

In the below script, there is passed var1 by reference to myDosFunc, so it can change the value.

How can the value of the referenced variable be get within the function without having to pass the variable and its value?

set "var1=Hello world"
Echo var1 before: %var1%
call :myDosFunc var1 "%var1%"
Echo var1 after : %var1%
goto :eof

:myDosFunc    -- passing a variable by reference, and changing value
echo   Notice that a variable passed by reference does NOT echo the value, and it echos the variable name instead.
echo   Arg1 variable name = '%~1' and Arg2 value = '%~2'
set "%~1=Good bye world!!!"
goto :eof

I tried the following variations, but none of them worked to get the value.

set "var1=Hello world"
Echo var1 before: %var1%
call :myDosFunc var1
Echo var1 after : %var1%
goto :eof

:myDosFunc    -- passing a variable by reference, and changing value
set "VarValue=%~1"
set "VarVal=%~1%"
echo   Arg1 variable name = '%~1' and to get value, tried this '%%%VarValue%%%' and this '%%VarValue%%' and this '%VarValue%' and this '%%%VarVal%%%' and this '%%VarVal%%' and this '%VarVal%'
set "%~1=Good bye world!"
goto :eof
0

2 Answers 2

2

Does this solve your problem?

@ECHO OFF
SETLOCAL
set "var1=Hello world"
Echo var1 before: %var1%
call :myDosFunc var1 
Echo var1 after : %var1%
goto :eof

:myDosFunc    -- passing a variable by reference, and changing value
echo   Notice that a variable passed by reference does NOT echo the value, and it echos the variable name instead.

CALL SET "arg2=%%%~1%%"
echo %arg2%
echo   Arg1 variable name = '%~1' and Arg2 value = '%~2'
set "%~1=Good bye world!!!"
goto :eof
1
  • Yes, that solves my problem. Thank you for the quick reply. Commented Jan 6 at 21:41
0

Just to clarify, I changed the variable names in the solution provided by Magoo.

set "var1=Hello world"
Echo var1 before: %var1%
call :myDosFunc var1
Echo var1 after : %var1%
goto :eof

:myDosFunc    -- passing a variable by reference, and changing value
CALL SET "arg1Value=%%%~1%%"
echo   Arg1 variable name = '%~1' and Arg1 value = %arg1Value%
set "%~1=Good bye world!"
goto :eof
1
  • Please note that this batch code does not work for any string value assigned to var1. Replace the line set "var1=Hello world" by the two lines @echo off & setlocal EnableExtensions DisableDelayedExpansion and set "var1=Development & Test 100%% (!)". Then run the batch file from within a command prompt window. Then run in the command prompt window echo echo Test.cmd is run!>test.cmd and run your batch file once again. Finally run del test.cmd and rename your batch file to test.cmd and run it in the command prompt window. You created an endless self-starting batch file.
    – Mofi
    Commented Jan 7 at 16:52

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.