The script package makes the setlocal variable access to other commands

I am writing a batch file to read the path from a file and set it to an environment variable. This batch file will be used (called) by many other batch files to get the variable. When writing the batch file I came across, the problem will have a variable extension, so I used SETLOCAL ENABLEDELAYEDEXPANSION to solve this problem. But at the same time, other batch files that use it cannot set variables.

Below is a 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 other batch file, I use the above batach file to get the variables set

  another.bat call getVariables.dat echo "%JAVA%" 

But echo is the print "" where it is not installed. If this is due to setlocal , how can I overcome this? I also need setlocal to delay expansion and occur at runtime. Any solution for this problem? Please help me.

+6
source share
4 answers

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%" ) 

Variables in block () expand to endlocal.

+10
source

This endlocal & set str=value will do wonders.

+4
source

It really depends on what you are doing - and you sent the full script.

First you have unbalanced % in %test.dat

Next, it's nice to name the batch files .bat not .dat

Further, if the sole purpose of this getVariables.bat is to set the fom variables of the string file (test.dat), for example

 JAVA_HOME=c:\whereverjavahomeis JAVA=c:\whereverjavais 

then

 @echo off if EXIST "test.dat" ( for /F "tokens=*" %%I in (test.dat) do set %%I ) 

quite adequate. That it is 4 lines (and all this can be compressed to 1 if you really try ...)

The point is that you only need enabledelayedexpansion and therefore setlocal to display the value of the variables you change WITHIN THE LOOP WHERE YOU'RE CHANGING THE VALUES . You will eventually delete these lines, and enabledelayedexpansion will lose its meaning.

For testing, you can write

 @echo off echo before...JAVA=%java% echo before...JAVA_HOME=%java_home% if EXIST "test.dat" ( for /F "tokens=*" %%I in (test.dat) do set %%I ) echo after....JAVA=%java% echo after....JAVA_HOME=%java_home% 

or even

 @echo off echo before&set java if EXIST "test.dat" ( for /F "tokens=*" %%I in (test.dat) do set %%I ) echo after&set java 

In fact, if getVariables.bat only ever been CALL ed, then even the @echo off line is redundant - if you @echo off from the calling party.

+2
source

go to cmd and find setx. it allows you to do system variables and all other types of things, for example, even find the x and y coordinates of a variable in a file.

0
source

All Articles