Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gradle execute command with environment variables and in other working dir

Gradle: Execute command within dir and with env vars

This is how to create a run function in Gradle (Groovy) to execute a command in a selectable working directory and with additional environment variables.

It is based on groovy's String.execute(...)

build.gradle

import java.nio.file.*

...

task doSomething {
  doLast {
    run 'echo Hello'
    run 'pwd', Paths.get("${project.projectDir}/subdir")
    run 'env', project.projectDir.toPath(), [ "XY" : "123"]
  }
}

def run (String command, Path workingDir=project.projectDir.toPath(), Map<String, String> additionalEnvVars = new HashMap()) {
  println "Running '${command}' in working dir '${workingDir}' with env ${additionalEnvVars}"

  def envVarMap = new HashMap<String, String>(System.env)   
  for (def entry : additionalEnvVars.entrySet()) {
    envVarMap.put(entry.getKey(), entry.getValue())
  }

  def envVars = envVarMap.entrySet().stream()
    .map {
      entry -> "${entry.getKey()}=${entry.getValue()}" 
    }.collect(Collectors.toList())

  def proc = command.execute(envVars, workingDir.toFile())
  proc.waitForProcessOutput(System.out, System.err)
  final int exitCode = proc.exitValue()
  if (exitCode != 0) {
    throw new RuntimeException("Command '${command}' (workdir '${workingDir}') exited with code ${exitCode}")
  }
}

Running with ./gradlew doSomething will result the following

$ ./gradlew doSomething
Hello
/home/me/myproject/subdir
...
XY=123

> Task :doSomething
Running 'echo Hello' in working dir '/home/me/myproject' with env [:]
Running 'pwd' in working dir '/home/me/myproject/subdir' with env [:]
Running 'env' in working dir '/home/me/myproject' with env [XY:123]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment