AJ-B29
AJ-B29

Reputation: 215

Set/Get Environment Variable from Java

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?

Upvotes: 1

Views: 847

Answers (2)

kostya
kostya

Reputation: 9559

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

Upvotes: 1

Siyuan Ren
Siyuan Ren

Reputation: 7844

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.

Upvotes: 1

Related Questions