Batch script make setlocal variable accessed by other batch files
batch-file, command, windows
Solution
To set multiple global variables to the value of local variables, use the following trick:
endlocal & (
set "globalvar1=%localvar1%"
set "globalvar2=%localvar2%"
set "globalvar3=%localvar3%"
)
The variables in the ( ) block are expanded before endlocal is executed.
Problem
I am writing a batch file to read a path from file and set it to environment variable. This batch file will be used (called) by many other batch files to get the variable. While writing the batch file I faced a problem will variable expansion so I used `SETLOCAL ENABLEDELAYEDEXPANSION` to overcome this issue. But doing so the other batch files which is using it are not able to get the variables set. Below is the batch script, ``` getVariables.bat @echo off SETLOCAL ENABLEDELAYEDEXPANSION if EXIST "test.dat" ( for /F "tokens=*" %%I in (test.dat) do set %%I echo setting JAVA_HOME to :: !JAVA_HOME! echo setting JAVA to !JAVA! ) ``` In my another batch file I am using the above batach file to get the variables set ``` another.bat call getVariables.dat echo "%JAVA%" ``` But echo is printing "", where it is not set. If this is because of `setlocal`, how can I overcome this ? I also need `setlocal` for delaying the expansion and to occur at execution time. How can I resolve this issue?