Batch files variables

How to pass variables between dos batch files

I spend a couple of hours today figuring out how to get the result from a DOS batch as a variable in another DOS batch file. I.e. you have a batch file A which calls another batch file B, which return sa variable you can use in bath file A.
Here is the solution I came up with:

My original called batch file calculated yesterdays date. I've been using a slightly modified version of Yesterday.bat from Rob van der Woude's Scripting Pages..

To keep this example simple I'll simulate the result of the called batch file with a simple file as:


:: Lots of complicated calculations which result in:
set yesterday = 20-01-2006
echo %yesterday%


:: Copy the output from executing another batch file into a variable
:: Execute outputVariable.bat and store batch files result in
:: variable yesterday
@FOR /F "tokens=*" %%i IN ('outputVariable.bat') DO set yesterday=%%i
echo %yesterday%

If you run readVariableFromOutput.bat it will show the value of %yesterday% which is now available for further processing. That's all there is too it.

If you are looking to pass a variable the other way. I.e. you have a batch file and want to call another batch file passing a variable instead of getting the returned value. Here is how to do that:


@echo off
set vara="Hello There"
set varb=67890

echo Variables set in caller.bat:
echo %vara%
echo %varb%

echo Calling passTo.bat
call passTo.bat %vara% %varb%


@echo off
echo Inside passTo.bat
set vara=%1
set varb=%2

echo vara: %vara%
echo varb: %varb%


Avoid using any spaces in the code to set the variables:

set vara="Hello There"

works whereas

set vara = "Hello There"

does not work.

I haven't looked into the possibilies of passing variables back and forth, but that can be easy figured out from these two examples.


You may republish this page as long as this message and an active link to is included.