问题
I am writing a shell script to read a file containing key=value pair and set those variables into environment variable. I tried with the below code,
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%
)
Assuming the test.dat has JAVA_HOME=c:\JDK1.6 and JAVA=c:\JDK1.6\bin\java
Running the above code is not setting these variables, even though I have set %%I statement in do. The two echo statements are not printing anything. What am I missing here ? Why the line which is read from file is not set into environment ?
回答1:
This does work here:
if exist test.dat for /f "delims=" %%i in (test.dat) do set %%i
set java
Output:
JAVA=c:\JDK1.6\bin\java
JAVA_HOME=c:\JDK1.6
回答2:
Environment variables enclosed within % characters are evaluated when the line of code is parsed, not when it is executed. If you want cmd to evaluate environment variables when the line of code is executed, you need to enable 'delayed variable expansion' and enclose the environment variable names within ! rather than %. For example:
...
setlocal enableextensions enabledelayedexpansion
...
if EXIST "test.txt" (
for /F "tokens=*" %%I in (%SEURAT_SERVER_DIR%\server-variables.dat) do @set %%I
echo setting JAVA_HOME to :: !JAVA_HOME!
echo setting JAVA to !JAVA!
)
echo JAVA_HOME=%JAVA_HOME%
echo JAVA=%JAVA%
Bill
来源:https://stackoverflow.com/questions/15481078/batch-script-read-file-and-set-to-environment-variable