Vatsalya Singh
Vatsalya Singh

Reputation: 43

How can i define and use functions in jenkinsfile?

I want to retrieve output from the git diff shell script into a variable and then run a user defined function on it. How can I declare these functions I want to write and how can I use them?

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"
        }
    }
}
}
```




Upvotes: 4

Views: 12549

Answers (1)

smelm
smelm

Reputation: 1334

You can define functions as you would in any Groovy script and you can capture the output of any shell command by passing it the parameter returnStdout. I think you need a scripted environment to call functions and define variables. So it would look like this:

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")
}

Upvotes: 9

Related Questions