Page 1 of 1

Passing variable from one batch file to another..

Posted: 08 Jul 2011 09:36
by ED209
Hi,

I'm not sure if this is possible with batch files but can a set of variables be passed from one batch file to another.. The idea is to have one main batch file which will in turn call some sub batch files.. The main batch file will have some variables set up so I'm wondering can the called sub batch files use those variables too or do they have to be defined again?

Thanks...

Re: Passing variable from one batch file to another..

Posted: 08 Jul 2011 10:00
by Ed Dyreen
batch.CMD

Code: Select all

set var=yes
call Mybatch.CMD Hello World
exit /b

Mybatch.CMD

Code: Select all

echo.%1
echo.%2
echo.%*
pause
call /?
pause
echo.var=%var%_
pause

Re: Passing variable from one batch file to another..

Posted: 08 Jul 2011 10:08
by ED209
Ok, maybe I didn't explain it too good..

I have a main.bat file with the below

Code: Select all

set "DIR1=C:\vartest1"
set "DIR2=C:\vartest2"
set "program=test.bat"

call %program% > teste_create.log 2>&1



test.bat

Code: Select all

echo Creating Directories
mkdir %DIR1%
mkdir %DIR2%



If I run the mail.bat file will the test.bat file be able to use the two dir variables set in the main file or do I need to set it a different way?

Re: Passing variable from one batch file to another..

Posted: 08 Jul 2011 11:35
by dbenham
ED209 wrote:Ok, maybe I didn't explain it too good..

You explained your question just fine... and Ed Dyreen gave you examples that would have demonstrated the answer had you run them and studied the code and the results.

The answer is YES. Your called subprogram will see the newly defined variables. Not only that, but the variables will continue to be defined even after your main.bat ends. If you don't want the variables to persist after main.bat ends then you should include SETLOCAL before you define the variables.

People don't mind helping, but you could have had your answer much faster had you run a simple test. Just include

Code: Select all

echo DIR1=%DIR1%
at the top of your test.bat and you will see that the value is still available.

Ed Dyreen was a bit cryptic in his response with regard to the CALL help and parameter passing included in his example. He was trying to demonstrate an alternative to passing values to a sub-program via variables. Instead he is suggesting using parameters appended to the CALL statement. But if your main.bat needs the variables as well then variables are a perfectly fine way to go.

Dave Benham