Gradle exec任务返回非零退出值,并且构建失败,但我希望不失败,而是执行另一个任务

Gradle exec task returns non-zero exit value and fails the build but I want to not fail and instead perform another task

我以非常默认的方式设置了一个exec任务,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
task myTask(type:Exec) {

    workingDir '.'

    commandLine './myscript.sh'

    doLast {
        if(execResult == 0) {
           //one thing
        } else {
           //another thing
        }
    }
}

但是不幸的是,当脚本抛出错误时,它从不执行doLast块。 相反,它将跳过该操作,并导致整个构建失败

Execution failed for task ':project:myTask'.
Process 'command './myscript.sh'' finished with non-zero exit value 1"

对我来说那没用。 使用非零退出值完成myscript.sh的整个想法是,因此我可以执行一些代码以对其进行响应。 我需要做些什么来使构建失败而不是捕获结果并执行响应操作? 谢谢您的帮助!


TL; DR-使用ignoreExitValue = true

当我阅读文档大约五十年代时,我终于看到有一个属性ignoreExitValue,默认为false。 但是,如果将其设置为true,则可以在doLast块中执行自己的任务。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
task myTask(type:Exec) {

    workingDir '.'

    commandLine './myscript.sh'

    ignoreExitValue true

    doLast {
        if(execResult.getExitValue() == 0) {
           //one thing
        } else {
           //another thing
        }
    }
}


如果ignoreExitValue答案不起作用,则另一解决方案是将commandLinetry { ... } catch (Exception e() { ... }包围。