How to achive bash like functionality (e.g. 'ls | grep mystuff') with gradle project.exec?

How would I achive bash like functionality with project.exec? Here’s some simple example, so executing something (command/shell script) and then grep some some mystuff out of it.

This doesn’t work:

task testTask
{ Task task ->
    doLast {
        task.project.exec {
            commandLine = ['ls', '|', 'grep mystuff']
        }
    }
}

I got it.

task featuresWaiting { Task task ->
        doLast {
            ByteArrayOutputStream stdOut = new ByteArrayOutputStream()
            task.project.exec {
                commandLine = [
                    "${task.project.projectDir}/show.sh",
                ]
                standardOutput = stdOut
            }
            def ByteArrayInputStream stdIn = new ByteArrayInputStream(stdOut.buf)
            stdOut = new ByteArrayOutputStream()
            task.project.exec {
                standardInput = stdIn
                standardOutput = stdOut
                commandLine = ['grep', '\-\-\-']
            }
            stdIn = new ByteArrayInputStream(stdOut.buf)
            stdOut = new ByteArrayOutputStream()
            task.project.exec {
                commandLine = ['grep' , '#feature']
                standardInput = stdIn
                standardOutput =stdOut
            }
            println stdOut
        }
    }

So for each pipe stdIn/stdOut pair is needed.

2 Likes

I’m not expert on this so can this be simplified somehow?

There are a few options. The simplest is to run via bash so you can use its command line interpreter…

task featuresWaiting(type: Exec) {
  commandLine "bash", "-c", "'${task.project.projectDir}/show.sh' | grep \-\-\- | grep #feature''
 }
1 Like