简体   繁体   English

在shell脚本中设置环境变量并在Java程序中访问

[英]Set environment variable in shell script and access in Java program

This question is a followup on Set environment variable in shell script/access in Java program . 这个问题是Java程序中shell脚本/访问中的Set环境变量的后续问题。 I am trying to fetch the environment variable in Java after running a shell script but unable to do so 我试图在运行Shell脚本后获取Java中的环境变量,但无法这样做

Shell Script: getDetails.sh: Shell脚本:getDetails.sh:

#!/bin/bash
# File: getDetails.sh
export userDetails="USER123"
# echo "User Details for App :$userDetails"

Java method: Java方法:

String details = new String("source " + "getDetails.sh");
ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", details);
Process getPwdProc = processBuilder.start();
System.out.println("Details - " + processBuilder.environment().get("userDetails"));

The java method returns/prints null for the environment variable - userDetails. java方法返回/打印环境变量-userDetails的null。

PS - Please note that the use of InputStream/BufferedReader to read the userDetails is not possible here as echoing the details is not allowed for the program/organization. PS-请注意,此处无法使用InputStream / BufferedReader读取userDetails,因为程序/组织不允许回显详细信息。

Exporting an environment variable from a bash process does not make it "global", it means that it is inherited (copied) to child processes. bash进程中导出环境变量并不能使其成为“全局”变量,这意味着它将被继承(复制)到子进程中。 That is, processes run by the bash process which exported it. 也就是说,由导出它的bash进程运行的进程。

Here Java is the parent , and there is no (legal) way to inject a variable into a parent process from a child. 这里Java是parent ,并且没有(合法的)方式将变量从子级注入到父级进程中。 The variable has to be set and exported before the Java is run. 必须在运行Java之前设置和导出变量。

I suggest a "wrapper" bash script that first exports the variable and then runs your Java application. 我建议使用“包装程序” bash脚本,该脚本首先导出变量,然后运行Java应用程序。

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

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