Siva
Siva

Reputation: 8058

Gradle - How to execute command line in doLast and get exit code?

task executeScript() {

    doFirst {
        exec {
            ignoreExitValue true
            commandLine "sh", "process.sh"
        }
    }

    doLast {
        if (execResult.exitValue == 0) {
            print "Success"
        } else {
            print "Fail"
        }
    }
}

I'm getting the following error

> Could not get unknown property 'execResult' for task ':core:executeScript' of type org.gradle.api.DefaultTask.

If I move the commandLine to configuration part everything works fine. But I want commandLine to be in action block so it wont run every time we execute some other gradle tasks.

Upvotes: 3

Views: 4075

Answers (2)

Dimitar II
Dimitar II

Reputation: 2519

Alternative syntax to execute external command and get its return code:

doLast {
    def process = "my command line".execute()
    process.waitFor()
    println "Exit code: " + process.exitValue()
}

Upvotes: 0

Daniel Taub
Daniel Taub

Reputation: 5379

Use gradle type for your task

task executeScript(type : Exec) {
    commandLine 'sh', 'process.sh'
    ignoreExitValue true

    doLast {
        if(execResult.exitValue == 0) {
            println "Success"
        } else {
            println "Fail"
        }
    }
}

This will work for you...

You can read more about the Exec task here

Upvotes: 2

Related Questions