1

I am setting an Environmental Variable in a .sh script as following :

export enVAr=$(/sbin/ip route|awk '/default/ { print $3 }')

and to get that Environmental Variable in Java I run the script:

ProcessBuilder pb = new ProcessBuilder("./setEnvIP.sh");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
{
    System.out.println(line);
}

but I get null for the env variable:

String setVar = System.getenv("enVAr");

How can I get the env variable?

2 Answers 2

1

When you execute the script with ProcessBuilder, you start a new process and change the environmental variables associated with that child process. The environment of the original Java application thus remains unmodified.

You need to execute the script before launching JVM for the environment modification to be effective in the Java process.

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

Comments

1

In the example you provided the environment variable is set only for a child process (setEnvIP.sh) and its children. It is not not set in the parent java process.

As far as I know there is no way to set environment variable in Java for the current process. You can only modify environment for a child process using ProcessBuilder.environment(): http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#environment()

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.