Collect environment variable in java after running script through ProcessBuilder

Why does the following code print false? I am trying to change an environment variable in test.sh script and compile 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")); } 

And the code for test.sh script is just

 set SOURCE=source 
0
source share
2 answers

The ProcessBuilder.environment() method is used to transfer the source environment to the process when start() called. You cannot get the subprocess environment from the parent process. This is not a Java limitation: you cannot even get the subprocess environment from the Bash script shell (or actually anything) that creates the subprocess. You need to find another means to pass information from the subprocess back to the parent process.

+1
source

In my opinion, you should change:

 ProcessBuilder processBuilder = new ProcessBuilder("test.sh"); 

to

 ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "test.sh"); processBuilder.directory(new File(the-dir-of-test.sh)); 
0
source

Source: https://habr.com/ru/post/1266575/


All Articles