简体   繁体   中英

How to pass groovy variable to shell script in Jenkinsfile?

In the Jenkinsfile under script section, I am using the following code to return output something like the following.

deleting 1
deleting 2
deleting 3

I have tried the following script but it seems to be not working.

script {
       prdirectory_lists = ['1','2','3']
       def size3 = prdirectory_lists.size()

        for(k=0;k<size3;k++){
        sh(returnStdout: true, script: 'ssh user1@192.168.1.12 echo deleting prdirectory_lists[k] ')
        //sh(returnStdout: true, script: 'ssh user1@192.168.1.12 echo deleting ${prdirectory_lists[k]} ')
        //sh(returnStdout: true, script: 'ssh user1@192.168.1.12 echo "deleting ${prdirectory_lists[k]}" ')
         }
}

Try this:

        sh returnStdout: true, 
           script: """ssh user1@192.168.1.12 echo "deleting ${prdirectory_lists[k]}" """

You have to use the correct String Interpolation which is "${variable}" to access the value of a variable.

sh(returnStdout: true, script: 'ssh user1@192.168.1.12 echo deleting "${prdirectory_lists[k]}" ')

The official Jenkins documentation has some good examples for this: String interpolation

You always use single quoted strings that do not have a string interpolation facility

The following should work:

def list = ['1','2','3']

list.each {item ->
   sh(returnStdout: true, script: "ssh user1@192.168.1.12 echo deleting $item")
}

All in all there are three types of strings in Groovy:

  1. Single Quoted - like usual java strings without string interpolation
  2. Double Quoted - Single line strings with an interpolation facility
  3. Triple Quoted - Multi line string with an interpolation facility

I believe Doble Quoted strings will suit you best in this case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM