从Gradle脚本运行shell命令

时间:2017-10-26 16:52:16

标签: shell gradle

我正在努力弄清楚如何从Gradle运行shell命令,因为Gradle似乎很难做到这一点。

这是命令:

git branch --merged | grep -v \* | grep -v master | grep -v develop | grep -v dmz | xargs git branch -D

这只是一个方便的命令来清理已合并的本地分支。

这是我创建的任务:

task gitCleanLocalBranches {
    doLast {
        exec {
            workingDir '.'
            commandLine 'git branch --merged | grep -v \\* | grep -v master | grep -v develop | grep -v dmz | xargs git branch -D'

        }
    }
}

任务失败:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':gitCleanLocalBranches'.
> A problem occurred starting process 'command 'git branch -a''

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':gitCleanLocalBranches'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
        ...
Caused by: org.gradle.process.internal.ExecException: A problem occurred starting process 'command 'git branch --merged | grep -v \* | grep -v master | grep -v develop | grep -v dmz | xargs git branch -D''
        at org.gradle.process.internal.DefaultExecHandle.execExceptionFor(DefaultExecHandle.java:222)
        ... 3 more
Caused by: net.rubygrapefruit.platform.NativeException: Could not start 'git branch --merged | grep -v \* | grep -v master | grep -v develop | grep -v dmz | xargs git branch -D'
        at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:27)
        ... 4 more
Caused by: java.io.IOException: Cannot run program "git branch --merged | grep -v \* | grep -v master | grep -v develop | grep -v dmz | xargs git branch -D" (in directory "/home/wlaw/sterlib"): error=2, No such file or directory
        at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:25)
        ... 6 more
Caused by: java.io.IOException: error=2, No such file or directory
        ... 7 more

所以我认为命令太复杂了,所以我尝试了更简单的方法,并将commandLine更改为:

commandLine 'git branch -a'

但是我得到了完全相同的错误。为什么Gradle无法在PATH环境变量中找到任何内容?

2 个答案:

答案 0 :(得分:11)

要执行的命令及其参数必须是单独的参数才能传递给commandLine,如下所示:

commandLine 'git', 'branch', '-a'

如果您想执行第一个示例中的复杂管道, 你可以将它包装在shell脚本中。

我无法测试这一点,但我认为这也应该有效:

commandLine 'sh', '-c', 'git branch --merged | grep -v -e \* -e master -e develop -e dmz | xargs git branch -D'

注意:我冒昧地简化了grep

最后,您还可以在.gitconfig中创建一个Git别名来包装复杂的管道。

答案 1 :(得分:1)

如果需要保存命令输出,可以执行以下操作:

def gitBranchA = "git branch -a".execute().text.trim()