简体   繁体   English

从Groovy中的文件加载环境变量

[英]Load environment variables from file in Groovy

I have an external file with variables that I would like to access in my groovy script. 我有一个带有要在groovy脚本中访问的变量的外部文件。

myfile.conf: myfile.conf:

variable1=Value1
export variable2=Value2

I want to do something like the following in my groovy script: 我想在groovy脚本中执行以下操作:

System.getenv("variable1")
System.getenv("variable2")

I have tried running "source myfile.conf".execute().waitFor() but I am unable to access these variables. 我尝试运行"source myfile.conf".execute().waitFor()但无法访问这些变量。

As others have said, strictly speaking you cannot alter environment variables of the running processs. 正如其他人所说,严格来说,您不能更改正在运行的进程的环境变量。

However, assuming you want to "do something like getenv" in order to get the values of certain variables following execution of your script, you can do something like this: 但是,假设您想“执行类似于getenv的操作”以便在执行脚本后获取某些变量的值,则可以执行以下操作:

def map = [:]
def envAsText = ['sh', '-c', 'source myfile.conf 2>&1 >/dev/null && env'].execute().text
envAsText.eachLine { (key,value) = it.split('=', 2); map[key] = value }

This creates an empty map, then executes child process to "source" your file, filter out all output while sourcing, then print environment with "env" command. 这将创建一个空的映射,然后执行子进程以“获取”您的文件,在采购时过滤掉所有输出,然后使用“ env”命令打印环境。 (also assuming unix-like system, which is implied from your "myfile.conf"). (还假设是类unix的系统,这是从“ myfile.conf”中隐含的)。 Finally, output is collected and stored to "map". 最后,将输出收集并存储到“地图”中。

After this, "map" contains all environment of your child process (now finished), including "variable2": 此后,“ map”包含子进程(现已完成)的所有环境,包括“ variable2”:

map['variable2'] // this contains "Value2"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM