Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kekru
Last active September 19, 2020 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kekru/0a4be8162d39f0f3ecfdc6a747df08d0 to your computer and use it in GitHub Desktop.
Save kekru/0a4be8162d39f0f3ecfdc6a747df08d0 to your computer and use it in GitHub Desktop.
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