Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

gradle

I have an exec task set up in a pretty default way, something like:

task myTask(type:Exec) {      workingDir '.'      commandLine './myscript.sh'      doLast {         if(execResult == 0) {            //one thing         } else {            //another thing         }     } } 

But unfortunately it never executes the doLast block when an error is thrown by the script. Instead it skips that and fails the entire build with

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

That's useless to me. The whole idea of myscript.sh finishing with a non-zero exit value is so I can then execute some code in response to it. What do I need to do to not fail the build but capture the result and perform an action in response? Thanks for the help!

like image 725
Scott Shipp Avatar asked Dec 12 '15 00:12

Scott Shipp


People also ask

How do I exclude tasks in Gradle?

Using Command Line Flags Task :compileTestJava > Task :processTestResources NO-SOURCE > Task :testClasses > Task :test > ... To skip any task from the Gradle build, we can use the -x or –exclude-task option. In this case, we'll use “-x test” to skip tests from the build.

Does Gradle build run all tasks?

You can execute multiple tasks from a single build file. Gradle can handle the build file using gradle command. This command will compile each task in such an order that they are listed and execute each task along with the dependencies using different options.


2 Answers

TL;DR - Use ignoreExitValue = true

When I read the documentation for about the fiftieth time, I finally saw that there is a property, ignoreExitValue, which defaults to false. But if you set it to true, you can then perform your own tasks in the doLast block.

task myTask(type:Exec) {      workingDir '.'      commandLine './myscript.sh'      ignoreExitValue true      doLast {         if(execResult.getExitValue() == 0) {            //one thing         } else {            //another thing         }     } } 
like image 186
Scott Shipp Avatar answered Sep 28 '22 21:09

Scott Shipp


If the ignoreExitValue answer is not working, another solution is to surround commandLine with a try { ... } catch (Exception e) { ... }.

like image 42
StPatrick Avatar answered Sep 28 '22 20:09

StPatrick