0

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Yash
  • 2,944
  • 7
  • 25
  • 43

1 Answers1

1

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.

haschibaschi
  • 2,734
  • 23
  • 31
  • Thanks, I learned a thing or two, but are you sure about that second point? In a common Groovy script this is not the case (as shown by OP), but is that different within a Jenkins Pipeline script? (I understand they are... special). Or do you mean we *should* use braces? (that I understand) – qlown May 26 '17 at 12:36
  • @qlown you are right, second point is not true. Adjusted my answer. – haschibaschi May 26 '17 at 13:12
  • @haschibaschi, Pls refer this link https://groovyconsole.appspot.com/script/5088905221111808 I still get the same issue – Yash May 26 '17 at 18:11
  • @Yash you can't execute this code block in the groovy console. `sh` is a dsl word implemented by jenkins. This only runs on jenkins. I tested the script in a jenkins pipeline job and it worked. – haschibaschi May 26 '17 at 19:18