在Jenkins管道的if语句中使用退出代码

lg40wkob  于 2023-02-07  发布在  Jenkins
关注(0)|答案(1)|浏览(193)

这是我的Jenkins管道,我试图在这里运行一个条件语句,基于前面命令的退出代码。

pipeline{
    agent any
    stages{
        stage('Test exitcode'){
            steps{
                script{
                    EX_CODE = sh(
                            script: 'echo hello-world',
                            returnStatus: true
                        )
                    if( env.EX_CODE == 0 ){
                        echo "Code is good with $EX_CODE"
                    }else{
                        echo "Code is Bad with $EX_CODE"
                    }
                }
            }
        }
    }
}

这是它的输出

Started by user Yatharth Sharma
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/workspace/devops/syntax-testing-pipeline
[Pipeline] { (hide)
[Pipeline] stage
[Pipeline] { (Test exitcode)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ echo hello-world
hello-world
[Pipeline] echo
Code is Bad with 0
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

我原以为这会返回Code is good,但这会打印出Code is Bad。有人能帮我解释一下为什么吗?

ha5z0ras

ha5z0ras1#

您正在将sh步骤方法中shell解释器命令的退出代码int返回值赋给变量EX_CODE。然后,您尝试访问条件中env对象成员的值,就好像它是环境变量而不是变量一样。您可以将该变量修改为环境变量,或者直接访问变量(更简单)。

EX_CODE = sh(script: 'echo hello-world', returnStatus: true)
if (EX_CODE == 0) {
  echo "Code is good with ${EX_CODE}"
}
else{
  echo "Code is Bad with ${EX_CODE}"
}

相关问题