如何在Jenkins 2.0管道作业中执行命令,然后返回stdout

use*_*266 20 groovy jenkins jenkins-workflow jenkins-pipeline jenkins-2

有没有更好的方法在Jenkins 2.0管道中运行shell任务,然后返回stdout命令.我能让它工作的唯一方法是将命令的输出传递给文件,然后将文件读入变量.

sh('git config --get remote.origin.url > GIT_URL')
def stdout = readFile('GIT_URL').trim()
Run Code Online (Sandbox Code Playgroud)

这似乎是一种非常糟糕的返回输出的方法.我希望我可以这样做:

def stdout = sh('git config --get remote.origin.url').stdout
Run Code Online (Sandbox Code Playgroud)

要么

def exitcode = sh('git config --get remote.origin.url').exitcode
Run Code Online (Sandbox Code Playgroud)

这可能吗?

phi*_*ert 21

是的,如luka5z所述,管道节点和进程插件版本2.4现在支持这种东西:

def stdout = sh(script: 'git config --get remote.origin.url', returnStdout: true)
println stdout

def retstat = sh(script: 'git config --get remote.origin.url', returnStatus: true)
println retstat
Run Code Online (Sandbox Code Playgroud)

似乎你试图在同一个脚本中返回两者,returnStatus将覆盖returnStdout,这有点不幸.

您可以在此处阅读官方文档中的更多内容

编辑:此外,它还允许您对失败/不稳定的构建状态进行更精细的控制.你可以在我的评论来看一个例子在这里

  • 我们可以一起使用它们吗?在一个变量中捕获 returnStdout 并在另一个中捕获 returnStatus ? 因为重复 sh 脚本两次并不酷 (3认同)

luk*_*a5z 19

更新

自2016年6月起,JENKINS-26133正式被标记为已解决.因此,在尝试下面的解决方法之前,首先尝试支持/的实现,这样可以使用 和参数.shbatreturnStdoutreturnStatus

解决方法

不幸的是,此功能仍然不受支持和缺失.欲了解更多信息,请参阅官方机票:

JENKINS-26133 Shell脚本获取/返回输出/状态状态:受让人:优先级:解决方案:打开Jesse Glick Major未解决


描述

目前sh没有有意义的返回值,并且如果退出状态不为零则抛出异常.很高兴有一个选项让它返回退出代码(零或不)作为整数值:

def r = sh script: 'someCommand', returnStatus: true
Run Code Online (Sandbox Code Playgroud)

目前的解决方法:

sh 'someCommand; echo $? > status' 
def r = readFile('status').trim()
Run Code Online (Sandbox Code Playgroud)

或者让它返回其标准输出(类似于shell反引号):

def lines = sh(script: 'dumpStuff.sh', returnStdout: true).split("\r?\n")
Run Code Online (Sandbox Code Playgroud)

解决方法:

sh 'dumpStuff.sh > result'
def lines = readFile('result').split("\r?\n")
Run Code Online (Sandbox Code Playgroud)

或者在标准输入上采取一些措施:

sh script: 'loadStuff.sh', stdin: someText
Run Code Online (Sandbox Code Playgroud)

解决方法:

writeFile file: 'input', text: someText >     sh 'loadStuff.sh < input'
Run Code Online (Sandbox Code Playgroud)

可能需要在持久任务中进行一些API更改.