How to execute a command with Gradle and the Exec Task?

About

How to execute a command with the exec task type:

Example by DSL

groovy

task myCommandTask(type: Exec) {
    workingDir "$projectDir"
    if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
        commandLine 'cmd', '/c', 'mycommand', 'arg1'
    } else {
        commandLine 'sh', '-c', 'mycommand', 'arg1'
    }
}

Kotlin

task<Exec>("echoNico") {
    workingDir("$projectDir")
    if (System.getProperty("os.name").toLowerCase().contains("windows")) {
        commandLine("cmd", "/c", "echo", "nico")
    } else {
        commandLine( "sh", "-c", "echo", "nico")
    }
}
  • Execution
gradle echoNico

With ExecSpec

https://docs.gradle.org/current/javadoc/org/gradle/process/ExecSpec.html

tasks.register("execMe") {
  
  
    println("Executing command")
    exec {
      commandLine(
        "command",
        "arg1",
        "arg2"
      )
    }

    println("Completed")

}





Discover More
How to skip a task if another task is executed in Gradle?

This page shows you how you can skip a task if another task is executed. It can happen in a test development when you have some build task you don't want to execute in a dev setting but that you want...



Share this page:
Follow us:
Task Runner