通过ProcessBuilder运行脚本后,在java中收集环境变量 [英] Collect environment variable in java after running script through ProcessBuilder
问题描述
为什么以下代码打印为false?我正在尝试test.sh脚本中的环境变量并在java中收集它。如果可能,请建议替代方法。
Why does the the following code print false ? I am trying to an environment variable in the test.sh script and collect it in java. Please suggest an alternative approach, if possible.
public static void main(String[] args){
ProcessBuilder processBuilder = new ProcessBuilder("test.sh");
Process process;
int exitCode;
try {
process = processBuilder.start();
exitCode = process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String, String>envVars = processBuilder.environment();
System.out.println(envVars.keySet().contains("SOURCE"));
}
并且test.sh脚本的代码只是
And the code for test.sh script is simply
set SOURCE=source
推荐答案
ProcessBuilder.environment()
方法用于在调用时将初始环境传递给进程启动()
。您无法从父进程获取子进程的环境。这不是Java限制:您甚至无法从创建子进程的Bash shell脚本(或实际上任何东西)获取子进程环境。您需要找到另一种方法将信息从子流程传递回父流程。
The ProcessBuilder.environment()
method is used for passing the initial environment to the process when you call start()
. You cannot get the environment of a subprocess from a parent process. This is not a Java restriction: you can't even get a subprocess environment from a Bash shell script (or in fact anything) that creates a subprocess. You need to find another means of communicating information from the subprocess back to the parent process.
这篇关于通过ProcessBuilder运行脚本后,在java中收集环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!