通过 Jenkins 执行 Groovy 命令:"find: missing argument to `-exec'"

Executing Groovy command through Jenkins: "find: missing argument to `-exec'"

我正在尝试使用 Jenkins 管道脚本 (groovy) 将生成的 war 文件从一个构建目录复制到另一个构建目录。我已经以 jenkins 用户的身份在系统本身上测试了 find/exec/cp 命令,从与脚本运行相同的工作区,它工作正常(直接从控制台复制粘贴)。

String buildNumber = env.BUILD_NUMBER

def sout = new StringBuffer()
def serr = new StringBuffer()

//Create package directory in jenkins job folder
def packageDir = "${env.JENKINS_HOME}/jobs/Package_Deploy_Pipeline/builds/${buildNumber}/package/"
def command = "mkdir ${packageDir}"
def proc = command.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(3000)
println "out> $sout err> $serr"

command = "find ${env.JENKINS_HOME}/jobs/myJob/builds/lastSuccessfulBuild/archive/build/libs/ -name *.war -exec cp {} ${packageDir} \;"
println command
proc = command.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(3000)
println "out> $sout err> $serr"

控制台输出中看到的错误是:

[Pipeline] echo
out>  err> 
[Pipeline] echo
find /var/lib/jenkins/jobs/myJob/builds/lastSuccessfulBuild/archive/build/libs/ -name *.war -exec cp {} /var/lib/jenkins/jobs/Package_Deploy_Pipeline/builds/23/package/ \;
[Pipeline] echo
out>  err> find: missing argument to `-exec'

编辑:我也试过 "*.war"'*.war'\;';'

我没有解决命令失败的原因,但我假设在链接命令时它的 groovys 转换为 sh 中断。我的解决方案是分解查找和复制命令。

location = "find ${env.JENKINS_HOME}/jobs/myJob/builds/lastSuccessfulBuild/archive/build/libs/ -name *.war".execute().text
command = "cp $location ${packageDir}myJob.war"
proc = command.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(3000)
println "out> $sout err> $serr"

Groovy

您遇到的错误问题可能与 \; 以及您正在转义 as for bash/sh 命令这一事实有关,而实际上您并没有使用 bash/sh , 但 运行 find 可执行文件。

需要对 -name 参数应用相同的方法,其中应从搜索模式中删除引号。

示例:

command = "find src -name *.txt -exec cp {} dst/ ;"
println "[cmd] ${command}"
proc = command.execute()

def sout = new StringBuffer()
def serr = new StringBuffer()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "[cmd.out] ${sout}"
println "[cmd.err] ${serr}"

詹金斯

如果您是 运行 来自 Jenkins 和 Pipeline 作业的代码,可能最方便的方法是使用内置的 sh 步骤。

sh: Shell Script

This step allows a Jenkins server or slave running on Linux or a Unix-like machine to execute a shell script.
Params:

script: String - the script to execute

sh "find src -name '*.txt' -exec cp {} dst/ \;"

More information on the Pipeline DSL can be found in the Pipeline tutorial.

纯粹Groovy

毕竟为什么不将 find 替换为 Groovy 代码:

("src" as File).eachFileRecurse{
    if (it.name ==~ ".*\.txt") {
        ...
    }
}

这样不是更优雅吗?

带有声明式管道的詹金斯只对我有效:

sh 'find . -ipath "*src/header.h" -exec rm {} ";"'