Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To pass variables set in jenkins pipeline to shell script

I want to send few parameters to one of my shell scripts written in linux server from a jenkins job. Below is my jenkins pipeline job:

def MY_VAR
def BUILD_NUMBER
pipeline {
    agent any
    stages {
        stage('Stage One') {
            steps {
                script {
                    BUILD_NUMBER={currentBuild.number}
                    MY_VAR ='abc'
                }                         
            }
        }
        stage('Stage Two') {
            steps {                    
                sh '''
                    cd /scripts/
                    ./my_scripts.sh $BUILD_NUMBER $MY_VAR'''
            }
        }
    }
}

Here I am able to send the value of BUILD_NUMBER but not of MY_VAR. It seems to me that since MY_VAR is set into pipeline that is why it is happening. Can anybody please help with the solution

like image 949
codeLover Avatar asked Oct 31 '25 03:10

codeLover


1 Answers

If you want to interpolate $MY_VAR when executing sh step, you need to replace single quotes with the double-quotes.

def MY_VAR
def BUILD_NUMBER
pipeline {
    agent any
    stages {
        stage('Stage One') {
            steps {
                script {
                    BUILD_NUMBER={currentBuild.number}
                    MY_VAR ='abc'
                }                         
            }
        }
        stage('Stage Two') {
            steps {                    
                sh """
                    cd /scripts/
                    ./my_scripts.sh $BUILD_NUMBER $MY_VAR"""
            }
        }
    }
}

The $BUILD_NUMBER worked, because pipeline exposes env.BUILD_NUMBER and this variable can be accessed inside the shell step as bash's $BUILD_NUMBER env variable. Alternatively, you could set MY_VAR as an environment variable and keep single quotes in the sh step. Something like this should do the trick:

pipeline {
    agent any
    stages {
        stage('Stage One') {
            steps {
                script {
                    //you can remove BUILD_NUMBER assignment - env.BUILD_NUMBER is already created.
                    //BUILD_NUMBER={currentBuild.number}
                    env.MY_VAR ='abc'
                }                         
            }
        }
        stage('Stage Two') {
            steps {                    
                sh '''
                    cd /scripts/
                    ./my_scripts.sh $BUILD_NUMBER $MY_VAR'''
            }
        }
    }
}

You can learn more about Jenkins Pipeline environment variables from one of my blog posts.

like image 177
Szymon Stepniak Avatar answered Nov 02 '25 19:11

Szymon Stepniak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!