如何在Jenkins声明性流水线中使用shell脚本if else条件块

3

如何在Jenkins声明性流水线中使用shell脚本的if-else条件块

下面是我想要在Jenkins流水线阶段运行的shell脚本命令,以及我们使用shell脚本/命令行运行它们的方法

#!/bin/sh
var=$(git status -s)
echo ${#var}
if [ ${#var} -eq 0 ]
then
  echo "tree is clean"
else
  echo "tree is dirty, please commit changes before running this"
  git add -A
  git commit -m "updated terraform files"
  git push
fi

echo "End of script"

这些步骤在Linux和Jenkins shell/命令提示符中正常工作。如何在Jenkins管道内复制相同的步骤?

我尝试过以下方法,但失败了。

# jenkins pipeline

pipeline {
    agent  any
    stages {
        stage('Test') {
            steps {
                sh 'node --version'
                sh 'pwd'
                sh 'sleep 15'
                script {
                    sh 'pwd'
                    sh 'var=$(git status -s)'
                    sh 'echo ${#var}' # till here it's working, but if block it's failing. I guess perhaps because if block is actually written in groovy syntax not linux/shell script 'if else' block
                     if ( ${#var} -eq 0 ) {
                         sh 'echo tree is clean'
                     }else {
                         sh 'echo tree is dirty please commit your code changes'
                     }
                }
                sh 'sleep 5'
            }
        }
    }
}

希望您能尽快回复。

1个回答

0

我知道这不是快速响应,但也许对未来的人们有用。

首先,您需要区分Jenkins变量和shell变量。 您定义的是shell变量,并希望在if语句中将其用作Jenkins变量。

正确的应用方式应该像这样:

# jenkins pipeline

pipeline {
    agent  any
    stages {
        stage('Test') {
            steps {
// This is definition of Jenkins variables
// Please be aware that you can refer to it only in current stage
                def nodeVersion = sh(script: "node --version", returnStdout: true).trim()
                def currentPath = sh(script: "pwd", returnStdout: true).trim()
                def gitStatus = sh(script: "git status -s", returnStdout: true).trim()

// This will make output of `gitStatus` global variable that you can use in any stage
                env.GIT_STATUS = gitStatus

// Now you can use this variable in Jenkins if statement
                if ( gitStatus == 0 ) {
                      sh 'echo tree is clean'
                } else {
                     sh 'echo tree is dirty please commit your code changes'
                }
                sh 'sleep 5'
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接