我在 Jenkinsfile (Groovy) 中有类似这样的内容,我想记录标准输出和退出码以便稍后使用该信息存储在一个变量中。
sh "ls -l"
如何实现这一点,特别是因为似乎无法在 Jenkinsfile
内部运行任何类型的 Groovy 代码?
我在 Jenkinsfile (Groovy) 中有类似这样的内容,我想记录标准输出和退出码以便稍后使用该信息存储在一个变量中。
sh "ls -l"
如何实现这一点,特别是因为似乎无法在 Jenkinsfile
内部运行任何类型的 Groovy 代码?
管道的最新版本sh
步骤使您可以执行以下操作;
// Git committer email
GIT_COMMIT_EMAIL = sh (
script: 'git --no-pager show -s --format=\'%ae\'',
returnStdout: true
).trim()
echo "Git committer email: ${GIT_COMMIT_EMAIL}"
另一个特性是 returnStatus
选项。
// Test commit message for flags
BUILD_FULL = sh (
script: "git log -1 --pretty=%B | grep '\\[jenkins-full]'",
returnStatus: true
) == 0
echo "Build full flag: ${BUILD_FULL}"
这些选项是基于此问题添加的。
有关sh
命令,请查看官方文档。
对于声明性管道(请参见注释),您需要将代码包装到script
步骤中:
script {
GIT_COMMIT_EMAIL = sh (
script: 'git --no-pager show -s --format=\'%ae\'',
returnStdout: true
).trim()
echo "Git committer email: ${GIT_COMMIT_EMAIL}"
}
WorkflowScript: 97: Expected a step @ line 97, column 17.
- Wrenchscript
步骤块内起作用。参见 https://jenkins.io/doc/book/pipeline/syntax/#declarative-steps。 - brass monkey当前的Pipeline版本原生支持returnStdout
和returnStatus
,这使得可以从sh
/bat
步骤获取输出或状态。
例如:
def ret = sh(script: 'uname', returnStdout: true)
println ret
官方文档。
script { }
包裹。 - x-yurish
的任何信息了... :( - Anentropic快速答案如下:
sh "ls -l > commandResult"
result = readFile('commandResult').trim()
我认为存在一项功能请求,允许获取sh步骤的结果,但据我所知,目前没有其他选项。
修改2:不确定是从哪个版本开始,但现在sh/bat步骤可以简单地返回标准输出:
def output = sh returnStdout: true, script: 'ls -l'
@
符号:
output = sh(script: 'command here', returnStdout: true).trim().readLines().drop(1).join(" ")
- itodd如果您想要获取标准输出并且知道该命令是否成功,只需使用returnStdout
并将其包装在异常处理程序中:
脚本化管道
try {
// Fails with non-zero exit if dir1 does not exist
def dir1 = sh(script:'ls -la dir1', returnStdout:true).trim()
} catch (Exception ex) {
println("Unable to read dir1: ${ex}")
}
输出:
[Pipeline] sh
[Test-Pipeline] Running shell script
+ ls -la dir1
ls: cannot access dir1: No such file or directory
[Pipeline] echo
unable to read dir1: hudson.AbortException: script returned exit code 2
不幸的是,hudson.AbortException缺少获取退出状态的有用方法,因此如果需要实际值,您需要从消息中解析它(唉!)
与Javadoc相反https://javadoc.jenkins-ci.org/hudson/AbortException.html,当捕获到此异常时,构建未失败。 它是在未被捕获时失败的!
更新:如果您还想要来自shell命令的STDERR输出,则不幸的是,Jenkins无法适当地支持常见的用例。 2017票JENKINS-44930卡在了一个主观的乒乓球状态中,没有向解决方案取得进展-请考虑将您的赞投票给它。
至于现在的解决方案,可能会有几种可能的方法:
a)将STDERR重定向到STDOUT2>&1
-但是您需要从主输出中解析它,并且如果命令失败,则不会获得输出-因为您在异常处理程序中。
b)将STDERR重定向到临时文件(名称提前准备)2>filename
(但记得在之后清理文件)-即主代码变为:
def stderrfile = 'stderr.out'
try {
def dir1 = sh(script:"ls -la dir1 2>${stderrfile}", returnStdout:true).trim()
} catch (Exception ex) {
def errmsg = readFile(stderrfile)
println("Unable to read dir1: ${ex} - ${errmsg}")
}
c)相反地,设置returnStatus=true
,摒弃异常处理程序并始终将输出捕获到文件中,即:
def outfile = 'stdout.out'
def status = sh(script:"ls -la dir1 >${outfile} 2>&1", returnStatus:true)
def output = readFile(outfile).trim()
if (status == 0) {
// output is directory listing from stdout
} else {
// output is error message from stderr
}
注意:上面的代码适用于 Unix/Linux 系统,而Windows需要完全不同的命令。
这是一个示例案例,我相信它将有意义!
node('master'){
stage('stage1'){
def commit = sh (returnStdout: true, script: '''echo hi
echo bye | grep -o "e"
date
echo lol''').split()
echo "${commit[-1]} "
}
}
对于那些需要在后续 shell 命令中使用输出结果的人,可以使用类似以下示例的方法:
stage('Show Files') {
environment {
MY_FILES = sh(script: 'cd mydir && ls -l', returnStdout: true)
}
steps {
sh '''
echo "$MY_FILES"
'''
}
}
我发现code maven上的例子非常有用。
script{
sh " 'shell command here' > command"
command_var = readFile('command').trim()
sh "export command_var=$command_var"
}
用您选择的命令替换shell命令。如果您正在使用Python代码,现在可以仅指定os.getenv("command_var"),它将返回先前执行的shell命令的输出。
如果您不只有一个sh命令而是一组sh命令,那么returnstdout就无法工作。
我曾经遇到过类似的问题,我采用了一种不太干净的方法来解决它,但最终它起到了作用并达到了目的。
解决方案 - 在shell块中,echo该值并将其添加到某个文件中。 在脚本块内部和外部的shell块之间,读取此文件,修剪它并将其分配给任何本地/参数/环境变量。
例如 -
steps {
script {
sh '''
echo $PATH>path.txt
// I am using '>' because I want to create a new file every time to get the newest value of PATH
'''
path = readFile(file: 'path.txt')
path = path.trim() //local groovy variable assignment
//One can assign these values to env and params as below -
env.PATH = path //if you want to assign it to env var
params.PATH = path //if you want to assign it to params var
}
}
./APP_TSBASE/app/team/i-home/deployments/ip-cc.war/cs_workflowReport.jar,configurable-wf-report,94,23crb1,artifact
./APP_TSBASE/app/team/i-home/deployments/ip.war/cs_workflowReport.jar,configurable-temppweb-report,394,rvu3crb1,artifact
========================
在这里想要获取模块名称第二个参数(configurable-wf-report),构建编号为第三个参数(94),提交标识符为第四个参数(23crb1)
def module = sh(script: """awk -F',' '{ print \$2 "," \$3 "," \$4 }' releaseModules.txt | sort -u """, returnStdout: true).trim()
echo module
List lines = module.split( '\n' ).findAll { !it.startsWith( ',' ) }
def buildid
def Modname
lines.each {
List det1 = it.split(',')
buildid=det1[1].trim()
Modname = det1[0].trim()
tag= det1[2].trim()
echo Modname
echo buildid
echo tag
}
最简单的方法是使用以下方式:
my_var=`echo 2`
echo $my_var
输出结果为:2
请注意,这里不是使用单引号而是反引号(`)。
ls -l
而不是echo 2
,它可以工作。实际上,我以前就用过这种方法,但一直在寻找替代方案,因为它不太可靠。我以这种方式在标准shell中捕获了更复杂命令的输出,但当移植到Jenkins的“sh”时,变量无法保留,原因未知。 - Nagev