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

    //获取标准输出
    //第一种
    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)
        echo "return exitValue :${exitValue}"
        if(exitValue != 0){
        	执行操作
        }
如果grep命令执行没有报错,正常情况下exitValue为0,报错则为非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()

相关资料:
https://stackoverflow.com/questions/36547680/how-to-do-i-get-the-output-of-a-shell-command-executed-using-into-a-variable-fro
https://issues.jenkins-ci.org/browse/JENKINS-26133
https://stackoverflow.com/questions/36956977/how-to-execute-a-command-in-a-jenkins-2-0-pipeline-job-and-then-return-the-stdou

  • 10
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值