Search code examples
gradlebuild.gradlegradle-plugingradlew

How can I only execute specific task in build.gradle?


build.gradle is:

task copy(type: Copy, group: "Custom", description: "Copies sources to the dest directory") {
    from "src"
    into "dest"
    println "copy"
}

task hello {
    println "hello"
}

And when I try with ./gradlew copy, both copy and hello are executed. Output like below:

> Configure project :
copy
hello

How can I only execute copy?


Solution

  • In your example, only the copy task is executed. However, both are configured.

    A Gradle build has three distinct phases in the build lifecycles:

    1. An initialization phase
    2. A configuration phase
    3. An execution phase

    By default, Gradle configures all tasks at start-up, though many types of configurations can be deferred (lazy configuration).

    The println statement you have in the hello task is part of the configuration and this is why you see it no matter what task you intend to execute. You can also see in the output that is under the > Configure project : header.

    If you want to only print "hello" when it actually executes, move it into a doLast block like this:

    task hello {
        doLast {
            println "hello"
        }
    }