首页 > 解决方案 > 如何检查方法是否在 Groovy 中返回非零退出代码

问题描述

我有一个 Jenkinsfile 项目,它要求我包含一个'if statement以确定某些方法中的 shell 命令是否返回0.

第一种方法method 1按预期工作。但是我想包括一个if statement跳过第二阶段,因为该 shell 命令method 2不会以0.

def method1(setup){
  sh """
  echo ${setup}
  """
}
def method2(setup){
  sh """
   ech ${setup}
  """
}
node {
  stage('print method1'){   
    method1('paul')
  }
// I need an if statement to skip this method since the if statement returns non=zero

  stage('This method should be skipped'){   
   if(method2 returns != 0) //This if condition fails but need something similar to this
    method1('paul')
    }
}

对此的任何帮助都非常感谢。

标签: groovyjenkins-pipeline

解决方案


您在示例中使用默认sh步骤执行,这意味着该命令不会返回退出代码。如果存在状态不是0这种情况,则管道将失败并出现异常。如果要返回退出状态并允许管道继续,则必须传递returnStatus: true选项,例如:

int status = sh(script: """
    echo ${setup}
""", returnStatus: true)

if (status != 0) {
    // do something
}

来源:sh步骤管道文档


推荐阅读