Groovy parameters are not visible in shell part of a Jenkinsfile

1.9k Views Asked by At

I'm facing a problem in Groovy script wherein the variable is not accessible in shell script part.

script-1:

 def a=20;
 println ("a is: $a");

output-1:

a is: 20

script-2:

def a=20;
println ("a is: $a");
sh '''echo a is $a''';

Output-2:

groovy.lang.MissingMethodException: No signature of method: Script1.sh() is applicable for argument types: (java.lang.String) values: [echo a is $a] Possible solutions: use([Ljava.lang.Object;), is(java.lang.Object), run(), run(), any(), with(groovy.lang.Closure) at Script1.run(Script1.groovy:3)

How can i get $a = 20 in the shell part sh. In other words what operations are required to pass the variable $a in shell script part.

I'm writing this script in context of a Jenkins pipeline where i'm facing a problem that groovy variables are not visible in the shell part.

1

There are 1 best solutions below

4
On

this works:

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                script {
                    // a is accessible globally in the Jenkinsfile
                    a = 20
                    // b is only accessible inside this script block
                    def b = 22
                    sh "echo a is $a"
                    sh "echo b is $b"
                }
            }
        }
    }
    post { 
        always { 
            sh "echo a is $a"
        }
    }
}

You should use double quote for the shell statement and not triple single quote.