Batch script read file and set to environment variable

你说的曾经没有我的故事 提交于 2019-12-13 07:06:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!