How to execute a shell command for each file in a Gradle file collection?

Bob Schaff picture Bob Schaff · Feb 27, 2014 · Viewed 9.1k times · Source

I've recently been directed to implement all build/release engineering jobs in Gradle.

So I'm new to Gradle and some things which are drop-dead obvious at a shell prompt are just hard to fathom in this brave new world.

My build creates a set of jar files.

I need to execute a shell task for each one of them

Something similar to:

task findBugs (type:Exec, dependsOn:  fb23) {commandLine 'java', '-jar',
'./findBugs/findbugs.jar',  '-textui', '-progress', '-xml', '-output',
'TrustManagerService.xml', 'TrustManagerService.jar'}

(I can't usethe FindBugs plug-in because we're in JDK8 - so I'm running FindBugs externally from a preview version...)

I can get a file collection and iterate over the file names with something like:

FileTree iotTree = fileTree(dir: '.')
iotTree.include '*.jar'
iotTree.each {
File file -> println file.name
println 'A file'
}

or

def iotJars = files(file('./jars').listFiles())
println ''
println iotJars
iotJars.each { File file -> println 'The next file is: ' + file.name }

But for the life of me I can't see how to execute a shell command for each filename returned...

Thoughts on the most straightforward way to do this??

By the way - what's the best way to include the line breaks in the code listing - I had to return and add CRs to each line to get them to break...:(

Answer

ditkin picture ditkin · Feb 27, 2014

You can use the execute method on a String to execute a shell command.

Here is an example task:

task executeExample << {
  FileTree ioTree = fileTree(dir: ".")
  ioTree.each { f ->
    def proc  = "ls -l ${f}".execute();
    proc.waitFor();
    println "return code: ${ proc.exitValue()}"
    println "stderr: ${proc.err.text}"
    println "stdout: ${proc.in.text}"
  }
}