Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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




like image 460
Vatsalya Singh Avatar asked Oct 27 '25 09:10

Vatsalya Singh


1 Answers

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")
}
like image 73
smelm Avatar answered Oct 30 '25 13:10

smelm