Gradle: Passing variable from one task to another

21,318

Solution 1

You can define an output variable outside of the doLast method, but in script root and then simply use it in another tasks. Just for example:

//the variable is defined within script root
def String variable

task task1 << {
    //but initialized only in the task's method
    variable = "some value"
}

task task2 << {
    //you can assign a variable to the local one
    def body = variable
    println(body)

    //or simply use the variable itself
    println(variable)
}
task2.dependsOn task1

Here are 2 tasks defined. Task2 depends on Task1, that means the second will run only after the first one. The variable of String type is declared in build script root and initialized in task1 doLast method (note, << is equals to doLast). Then the variable is initialized, it could be used by any other task.

Solution 2

I think global properties should be avoided and gradle offers you a nice way to do so by adding properties to a task:

task task1 {
     doLast {
          task1.ext.variable = "some value"
     }
}

task task2 {
    dependsOn task1
    doLast { 
        println(task1.variable)
    }
}
Share:
21,318
crystallinity
Author by

crystallinity

Updated on July 16, 2022

Comments

  • crystallinity
    crystallinity almost 2 years

    I want to pass a variable from one task to another, in the same build.gradle file. My first gradle task pulls the last commit message, and I need this message passed to another task. The code is below. Thanks for help in advance.

    task gitMsg(type:Exec){
        commandLine 'git', 'log', '-1', '--oneline'
        standardOutput = new ByteArrayOutputStream()
        doLast {
           String output = standardOutput.toString()
        }
    }
    

    I want to pass the variable 'output' into the task below.

    task notifyTaskUpcoming << {
        def to = System.getProperty("to")
        def subj = System.getProperty('subj') 
        def body = "Hello... "
        sendmail(to, subj, body)
    }
    

    I want to incorporate the git message into 'body'.