Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variables from one batch file to another batch file?

Tags:

batch-file

How do I write a batch file which gets an input variable and sends it to another batch file to be processed.

Batch 1

I don't know how to send a variable to batch 2 which is my problem here.

Batch 2

if %variable%==1 goto Example
goto :EOF

:Example
echo YaY
like image 941
Jonathan Viju Mathai Avatar asked Dec 22 '14 01:12

Jonathan Viju Mathai


3 Answers

You don't need to do anything at all. Variables set in a batch file are visible in a batch file that it calls.

Example

test1.bat

@echo off
set x=7
call test2.bat
set x=3
call test2.bat
pause

test2.bat

echo In test2.bat with x = %x%.

Output

... when test1.bat runs.

In test2.bat with x = 7.
In test2.bat with x = 3.
Press any key to continue . . .
like image 112
Ivan Avatar answered Sep 18 '22 15:09

Ivan


You can pass in the batch1.bat variables as arguments to batch2.bat.

arg_batch1.bat

@echo off
cls

set file_var1=world
set file_var2=%computername%
call arg_batch2.bat %file_var1% %file_var2%

:: Note that after batch2.bat runs, the flow returns here, but since there's
:: nothing left to run, the code ends, giving the appearance of ending with
:: batch2.bat being the end of the code.

arg_batch2.bat

@echo off

:: There should really be error checking here to ensure a
:: valid string is passed, but this is just an example.
set arg1=%~1
set arg2=%~2

echo Hello, %arg1%! My name is %arg2%.

If you need to run the scripts simultaneously, you can use a temporary file.

file_batch1.bat

@echo off
set var=world

:: Store the variable name and value in the form var=value
:: > will overwrite any existing data in args.txt, use >> to add to the end
echo var1=world>args.txt
echo var2=%COMPUTERNAME%>>args.txt

call file_batch2.bat

file_batch2.bat

@echo off
cls

:: Get the variable value from args.txt
:: Again, there is ideally some error checking here, but this is an example
:: Set no delimiters so that the entire line is processed at once
for /f "delims=" %%A in (args.txt) do (
    set %%A
)

echo Hello, %var1%! My name is %var2%.
like image 30
SomethingDark Avatar answered Sep 17 '22 15:09

SomethingDark


If you are reading the answers and still getting problems, you may be using setlocal wrong.

setlocal works like namespaces with endlocal closing the last opened namespace.

If you put endlocal at the end of your callee as I used to do by default, your variable will be lost in the previously opened setlocal.

As long as your variable is set in the same "local" as your caller file's you will be ok.

like image 29
Dominic Grenier Avatar answered Sep 18 '22 15:09

Dominic Grenier