Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gradle exec: how to print error output?

Gradle task: start a service

task startService(type: Exec) {
    standardOutput = new ByteArrayOutputStream()
    errorOutput = new ByteArrayOutputStream()

    commandLine 'cmd', '/c', 'net', 'start', 'serviceFoo'

    doLast {
        println standardOutput.toString()
        println errorOutput.toString()
    }

}

running "net start serviceFoo" will print "access denied" message on windows. but gradle startService, no message is printed.

UPDATE

tried it on Windows command prompt (admin):

 commandLine 'net', 'start', 'serviceFoo'

Error message:

* What went wrong:
Execution failed for task ':startService'.
> Process 'command 'net'' finished with non-zero exit value 2

On command prompt (admin):

 net start serviceFoo

Successful.

like image 560
eastwater Avatar asked Oct 29 '25 01:10

eastwater


2 Answers

Gradle will by default throw an exception and terminate when receiving non-zero result codes from commands. You can disable this by setting the property

ignoreExitValue true

in your task. Normally you'd also wanna check for it yourself then, eg.

doLast {
  if (execResult.getExitValue() != 0) {
    ...
  }
}
like image 69
Espen Avatar answered Nov 01 '25 14:11

Espen


Here is what I am using for newer version of gradle:

task myCommandLineTask(type: Exec) {
    commandLine 'my_command.sh'

    ignoreExitValue = true
    standardOutput = new ByteArrayOutputStream()
    doLast {
        def exitCode = executionResult.get().exitValue
        if (exitCode != 0) {
            def result = standardOutput.toString()
            println result
            throw new GradleException("Failed to run command (exit code:$exitCode)")
        }
    }
}
like image 42
OlivierM Avatar answered Nov 01 '25 14:11

OlivierM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!