本文介绍了批处理脚本读取文件,并设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个shell脚本读取包含key = value对一个文件,并设置这些变量到环境变量。我试着用下面的code,

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

假设 TEST.DAT JAVA_HOME = C:\\ JDK1.6 JAVA = C:\\ JDK1.6 \\ BIN \\ java中
运行上面的code未设置这些变量,即使我有设置%%我不要语句。这两个print语句不打印任何东西。我缺少的是在这里吗?为什么它是从文件中读取行没有设置成环境?

Assuming the test.dat has JAVA_HOME=c:\JDK1.6 and JAVA=c:\JDK1.6\bin\javaRunning 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 ?

推荐答案

在封闭的环境变量的当code的行的解析的角色进行评估,不是当它的执行的。如果你想CMD执行code线时,评估环境变量,你需要启用延迟的变量扩充,并在而非%。例如:

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%

比尔

这篇关于批处理脚本读取文件,并设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:23