'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.



Solution 1:[1]

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

Solution 2:[2]

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()
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Taub
Solution 2 Dimitar II