当前位置: 代码网 > 服务器>服务器>Linux > jenkins pipeline中获取shell命令的标准输出或者状态的方法小结

jenkins pipeline中获取shell命令的标准输出或者状态的方法小结

2024年05月15日 Linux 我要评论
//获取标准输出//第一种result = sh returnstdout: true ,script: "<shell command>"result = result.trim()//
//获取标准输出
//第一种
result = sh returnstdout: true ,script: "<shell command>"
result = result.trim()
//第二种
result = sh(script: "<shell command>", returnstdout: true).trim()
//第三种
sh "<shell command> > commandresult"
result = readfile('commandresult').trim()
//获取执行状态
//第一种
result = sh returnstatus: true ,script: "<shell command>"
result = result.trim()
//第二种
result = sh(script: "<shell command>", returnstatus: true).trim()
//第三种
sh '<shell command>; echo $? > status'
def r = readfile('status').trim()
//无需返回值,仅执行shell命令
//最简单的方式
sh '<shell command>'

例如:
工作中需要获取shell 命令的执行状态,返回0或者非0
groovy语句写法为:

def exitvalue = sh(script: "grep -i 'xxx' /etc/myfolder", returnstatus: true)
// 如果grep命令执行没有报错,正常情况下exitvalue为0,报错则为非0
echo "return exitvalue :${exitvalue}"
if(exitvalue != 0){
   //执行操作
}

需要注意的是当命令中存在重定向的时候,会出现返回状态异常,因为我们要返回状态,删除重定向(&>/dev/null)即可,比如:

def exitvalue = sh(script: "grep -i 'xxx' /etc/myfolder &>/dev/null", returnstatus: true)
// xxx不存在,正常逻辑是返回非0,但是实际中返回的是0 。
// 可以理解为先执行命令然后赋值操作,类似下面的动作:(个人理解)
sh "ls -l > commandresult"
result = readfile('commandresult').trim()

groovy中存在另外一种解析shell脚本的方法,在jenkins pipeline中会使用会报异常,jenkins相关资料中也没有看到此种用法,应该是不支持

groovy.lang.missingpropertyexception: no such property: rhel for class: groovy.lang.binding

写法为:

def command = "git log"
def proc = command.execute()
proc.waitfor()
def status = proc.exitvalue()

到此这篇关于jenkins pipeline中如何获取shell命令的标准输出或者状态的文章就介绍到这了,更多相关jenkins pipeline获取shell命令内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com