tags:

views:

94

answers:

2

I am trying to use groovy to do shell scripting on unix, but I am not having any luck having one process retain the environment variables changed by another process. For example,

    def p1 = ["bash", "-c", "source /some/setEnv.sh"].execute()

Now, I would like a second process, p2, to inherit the environment variables that was set in p1. How can I do this? I don't see anything in java.lang.Process or its groovy extension that would spit out the environment variables after the process has executed.

+1  A: 

No. You need the second process to be executed from the first (i.e. the one setting the environment variables).

Have you thought about

  1. embedding the script setting the env variables in the second process ?
  2. getting the first process to set the environment variables, dump them out, and have the Java process read them and set the variables whilst invoking the second process (via Runtime.exec) .
Brian Agnew
Also, consider creating a temp script file embedding both the scripts you want to run and running that in bash.
binil
A: 

If you have to get environment veriables defined in a shell script do something like this:

def p = ["bash", "-c", "source /some/setEnv.sh ; somecmd /foo/bar"].execute()

This will run somecmd with the environment variables defined by /some/setEnv.sh.

A more complicated alternative might be:

  1. Run bash -c source ; env from Java
  2. Parse the output of the above to extract the effective environment variables and turn them into a Java environment variables map.
  3. Create / run the process you called p2 with the new environment.

It is important to understand that this is a consequence of the way that UNIX/Linux works, not of a shortcoming of the Java APIs. UNIX/Linux say that the "scope" of environment variables is an OS-level process, and that one process cannot read or set the environment variables of another process. The only time at which there is transfer of environment variable state from one process to another is when a child process is created.

Stephen C
Since I need to run a series of unix commands that depends on /some/setEnv.sh, I think your more complicated alternative is probably the way to go. I guess another alternative is to run /some/setEnv.sh in a Unix shell and then call the Groovy script from that same Unix shell process.
Eric Leung
Your last idea is the simplest/best, IMO.
Stephen C