3

The article "Passing by Reference" in http://ss64.com/nt/syntax-args.html mentions the following:

In addition to passing numeric or string values on the command line, it is also possible to pass a variable name and then use the variable to transfer data between scripts or subroutines.

But how do I do it? When I set the value of a variable and pass it's name as in

set parm=42
call sub.bat parm

how do I use it in sub.bat?

mkluwe
  • 3,823
  • 2
  • 28
  • 45

3 Answers3

7

Via delayed exapansion

@echo off
setlocal
set var1=value1
set var2=value2
call :sub var1
call :sub var2
exit /b

:sub
setlocal enableDelayedExpansion
echo %~1=!%~1!
exit /b

-- OUTPUT --

var1=value1
var2=value2
dbenham
  • 127,446
  • 28
  • 251
  • 390
0

Reference them by name, 2.bat run from 1.bat will inherit the same environment block, so

1.BAT

set parm=42
echo parm is '%parm%'
call 2.bat
echo parm is '%parm%'

2.BAT

set parm=XXX%parm%XXX

Would print:

parm is '42'
parm is 'XXX42XXX'

(Using call sub.bat %parm% would make a copy of parm available to sub.bat in %1)

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • That's clear to me, but the text I cited mentions "passing a variable name" (but without giving an example). – mkluwe Jan 15 '13 at 13:55
0

I know this question is very old, but I wanted to clarify something: "Passing by Reference" in this context does not mean you're passing a pointer around.

You're literally just passing the name of the variable as a string, then accessing the variable from the subroutine.

It works because environment variables use dynamic scoping - variables set in the caller are available to the callee, unless it shadows them by using SetLocal and then reusing the name.

SetLocal EnableDelayedExpansion
set "parm=Hello"
call :subroutine parm
REM The below will print "Hello world".
echo "%parm%"
exit /b

:subroutine
REM Now %1 contains the value "parm"
set "%1=!%1! world"
REM Now variable "parm" contains "Hello world"
exit /b

If the subroutine uses SetLocal itself, you have to use EndLocal to avoid shadowing the original variable:

EndLocal & set "%1=!%1! %local%"

But ultimately there's nothing special about the value that was passed; it's just a variable name that you use in set, which happens to correspond to an existing variable in the outer scope.