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:

outputVariable.bat

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

readVariableFromOutput.bat

:: 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:

caller.bat

@echo off
cls
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%

passTo.bat

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

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

Note:

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.

Copyright

You may republish this page as long as this message and an active link to http://www.marijn.org/archive/2006/batch-files-variables is included.