Home > Back-end >  How to use for loop with def list in Jenkins declarative pipeline
How to use for loop with def list in Jenkins declarative pipeline

Time:11-02

I have used for-loop in my script to run one by one which is mentioned in def data it is executing in how many values are given in def data but inside def data the word in not picking and not applying to the sentence.

Help me to slove this issue that help me to slove the original issue

Example

Def data = [ "apple","orange" ]

Stage(create sentence){

Steps{

Script {

For (x in data){

 Sh 'the fruit name is ${x}

}

}

}

}

Excepted output

  1. the fruit name is apple

  2. the fruit name is orange

But my output be like

  1. the fruit name is

  2. the fruit name is

CodePudding user response:

If you want to interpolate the variable in sh block, use double quotes to surround it.

Sh "the fruit name is ${x}"

CodePudding user response:

To use loop in this case you don't need for, you can simply iterate in the list you have.

To iterate only value:

data.each{
        println it
    }

OR

data.each {val-> 
             println(val)
          }
       

To iterate Value with index:

data.eachWithIndex{it,index->
            println "value "   it   " at index "  index
    }
  • Related