首页 > 解决方案 > 如何在 jenkinsfile 中定义和使用函数?

问题描述

我想将 git diff shell 脚本的输出检索到一个变量中,然后在其上运行一个用户定义的函数。我如何声明我想编写的这些函数以及如何使用它们?

pipeline{
agent any
parameters {
        string(name: 'branchA', defaultValue: 'master', description: 'Comapare which branch?')

        string(name: 'branchB', defaultValue: 'dev', description: 'Compare with which branch?')
}

stages {
    stage('Build') {
        steps{
            checkout([$class: 'GitSCM',
                branches: [[name: '*/master']],
                doGenerateSubmoduleConfigurations: false,
                extensions: [[$class: 'CleanBeforeCheckout']],
                submoduleCfg: [],
                userRemoteConfigs:  [[credentialsId: 'gitCreds', url: "https://github.com/DialgicMew/example.git"]]])
 
                sh "git diff --name-only remotes/origin/${params.branchA} remotes/origin/${params.branchB}"    
         }
    
    stage('Functions on the result') {
        steps{
            echo "Functions to be used here"
        }
    }
}
}
```




标签: jenkinsjenkins-pipelinejenkins-groovy

解决方案


您可以像在任何 Groovy 脚本中一样定义函数,并且可以通过传递参数returnStdout来捕获任何 shell 命令的输出。我认为您需要一个脚本环境来调用函数和定义变量。所以它看起来像这样:

pipeline{
    // your pipeline
    scripted {
        def output = sh returnStdout: true, script: "git diff ..."
        def result = workWithOutput(output)
        println result
    }

}

def workWithOutput(text){
    return text.replace("foo", "bar")
}

推荐阅读