1

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"));
}

And the code for test.sh script is simply

set SOURCE=source
2
  • I think it should be export SOURCE=source if you in *nix environment Commented Jun 6, 2016 at 9:50
  • tried export, did not work Commented Jun 6, 2016 at 9:56

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.