0

I've a global variable in pipeline say BACKUP_DIR_NAME and in shell script which is inside pipeline, I want to build path using it hence have following code -

BACKUP_DIR_NAME="10-04-2020"

pipeline {
    agent any

    stages {

        stage('First') {
            steps {
                script {

                    sh '''
                       BACKUP_DIR_PATH="/home/oracle/SeleniumFramework/SeleniumResultsBackup/"$BACKUP_DIR_NAME"/"
                        echo "Directory path is "$BACKUP_DIR_PATH
                        '''

                }
            }
        }
    }
}

When executed this, I can see value of BACKUP_DIR_NAME is evaluated as empty. Could you please help me to correct above code?

Alpha
  • 13,320
  • 27
  • 96
  • 163
  • Does this answer your question? [How to use pom version in shell command in jenkinsfile?](https://stackoverflow.com/questions/60971483/how-to-use-pom-version-in-shell-command-in-jenkinsfile) – Szymon Stepniak Apr 10 '20 at 11:05
  • I tried answer for the above suggested question. But results into error - `groovy.lang.MissingPropertyException: No such property: BACKUP_DIR_PATH for class: groovy.lang.Binding` – Alpha Apr 10 '20 at 11:17
  • Does this answer your question? [How to pass variables from Jenkinsfile to shell command](https://stackoverflow.com/questions/41539076/how-to-pass-variables-from-jenkinsfile-to-shell-command) – Matthew Schuchard Apr 10 '20 at 11:31

1 Answers1

0

You mix two types of variables in your sh step. In the first line, you are trying to access the Groovy variable and interpolate its value to construct shell variable. In the second line, you expect to access this shell variable.

To satisfy the first part, you need to use double quotes to construct a Groovy string that supports variables interpolation. To satisfy the second part, you need to escape \$ to prevent $BACKUP_DIR_PATH from being interpolated.

BACKUP_DIR_NAME="10-04-2020"

pipeline {
    agent any

    stages {

        stage('First') {
            steps {
                script {
                    sh """
                       BACKUP_DIR_PATH="/home/oracle/SeleniumFramework/SeleniumResultsBackup/"$BACKUP_DIR_NAME"/"
                        echo "Directory path is "\$BACKUP_DIR_PATH
                        """
                }
            }
        }
    }
}
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131