groovy - 如何检查方法是否在 Groovy 中返回非零退出代码

标签 groovy jenkins-pipeline

我有一个 Jenkinsfile 项目,它要求我包含一个 'if 语句 以确定某些方法中的 shell 命令是否返回 0 之外的退出代码。

第一种方法 方法 1 按预期工作。但是我想包含一个 if 语句 来跳过第二阶段,因为 method 2 中的 shell 命令不会以 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')
    }
}

非常感谢您对此提供的任何帮助。

最佳答案

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

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

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

来源:sh step pipeline documentation

关于groovy - 如何检查方法是否在 Groovy 中返回非零退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52020910/

相关文章:

parsing - groovy如何区分字符串的除法?

Jenkins 文件 : publish test results even if test step fails

docker - 如何在 docker 容器中使用 Jenkins 工具安装?

jenkins - Jenkins 管道中的 Artifactory : org. codehaus.groovy.runtime.GStringImpl 无法转换为 java.lang.String

调试 groovy 脚本 elasticsearch

grails - 无法解析AsyncHttpBuilder类

java - Grails 脚手架不存储给定域结构的引用

jenkins - 如何从共享库 src 文件运行完整的 Jenkins 脚本化管道阶段

jenkins - 如何在 Jenkins 声明式管道中使用 Throttle 并发构建

jenkins - 在哪里设置 -Dorg.jenkinsci.plugins.durabletask.BourneShellScript.HEARTBEAT_CHECK_INTERVAL=300