2

I want to run a command line with Gradle that this command has an output.
I run this command in windows powershell:
./mybat.bat myArgs when I hit enter, it will print some digit, like this:
123456
I want to run this command with gradle and save this result(123456)
here is some code that I written in android build.gradle file:

task getSomeOutput(type: Exec) {
    workingDir "${buildDir}/output"
    commandLine 'powershell', './mybat.bat' , 'foo'//this is myArgs for example
}

this works and prints the value 123456, but I want to save it in a variable, how can I do that?

OneDev
  • 557
  • 3
  • 14
  • 1
    Does this answer your question? [How to use exec() output in gradle](https://stackoverflow.com/questions/11093223/how-to-use-exec-output-in-gradle) – swpalmer Jan 16 '22 at 01:21
  • @swpalmer yes, but with a little difference :), thank you very much, this may be useful for someone else. – OneDev Jan 16 '22 at 07:43

2 Answers2

1

As you can see in the official doc HERE

This can be achieved with the following task

task executeCMD(type:Exec) {
  workingDir '.'
  commandLine 'mybat.bat', '>', 'log.txt'
     doLast {
         println "Executed!"
     }
 }

This will send the output of mybat.bat execution and set the results into a txt file called log .

the . is the directory where you have the script .

in my case its a project root directory .

George
  • 2,292
  • 2
  • 10
  • 21
1

the best approach I found is to add '/c' to commandLine arguments and use standardOutput, here some code that might help other people:

task getSomeOutput(type: Exec) {
    workingDir "${buildDir}/output"
    commandLine 'powershell', '/c', './mybat.bat' , 'foo'//this is myArgs for example
    standardOutput = new ByteArrayOutputStream()
    doLast {
        def result = standardOutput.toString()
        println "the result value is: $result"
    }    
}
OneDev
  • 557
  • 3
  • 14