Ahmed
Ahmed

Reputation: 3260

Writing environment variable through gradle doesnt show up in System Variables

I am writing a gradle script that sets an environment variable by executing shell script (in gradle). The script runs fine but I never saw it writing the results to system environment variables.

Gradle:

def executeOnShell() {
  String command = "export key=value"
  return executeOnShell(command, new File(System.properties.'user.dir'))
}

private def executeOnShell(String command, File workingDir) {
  println command
  def process = new ProcessBuilder(addShellPrefix(command))
                                    .directory(workingDir)
                                    .redirectErrorStream(true) 
                                    .start()
  process.inputStream.eachLine {println it}
  process.waitFor();
  return process.exitValue()
}

private def addShellPrefix(String command) {
  commandArray = new String[3]
  commandArray[0] = "sh"
  commandArray[1] = "-c"
  commandArray[2] = command
  return commandArray
}

When I run env command on my shell, it doesn't show anything written in system environment variables. Can someone please point out what am I doing wrong and how can I fix it?

Note: I am using Mac, so its a terminal. Writing env should return all of the environment variables.

Thanks!

Upvotes: 1

Views: 1569

Answers (1)

Lesmana
Lesmana

Reputation: 27033

The problem is you are trying to set an environment variable by executing a script. Two scripts even, first a gradle script then a shell script, if I understand your description correctly.

The environment variables of a process may only be changed by the process itself (under normal conditions). When you execute another process then that new process can only change its own environment variables, never those of it's parent or any other process.

So in your case you execute a gradle script which executes a shell script (a shell command) which adds an environment variable. That variable is added to the environment of the shell process inside the graddle process, but not to the environment of the graddle process. When the shell process terminates and then the gradle process terminates you are left with a shell with an unchanged environment.

What do you want to achieve? Do you want to have the variable set in your shell for further use? Then use source (or equivalent if your shell is not bash). Do you want to have the environment variable set in the gradle process? Then look up the documentation of gradle on how to set environment variables.

See also: the difference between sourcing and executing which explains why an environment variable set by an executed script does not stick in the parent process.

Upvotes: 2

Related Questions