问题
As stated in the title, I'm attempting to loop over an ArrayList
of strings in a Jenkins Groovy Pipeline script (using scripted Pipeline syntax). Let me lay out the entire "problem" for you.
I start with a string of filesystem locations separated by spaces: "/var/x /var/y /var/z ... " like so. I loop over this string adding each character to a temp string
. And then when I reach a space, I add that temp string to the array and restart. Here's some code showing how I do this:
def full_string = "/var/x /var/y /var/z"
def temp = ""
def arr = [] as ArrayList
full_string.each {
if ( "$it" == " " ) {
arr.add("$temp") <---- have also tried ( arr << "$temp" )
temp = ""
} else {
temp = "$temp" + "$it"
}
}
// if statement to catch last element
See, the problem with this is that if I later go to loop over the array it decides to loop over every individual char instead of the entire /var/x
string like I want it to.
I'm new to Groovy so I've been learning as I build this pipeline. Using Jenkins version 2.190.1 if that helps at all. I've looked around on SO and Groovy docs, as well as the pipeline syntax docs on Jenkins. Can't seem to find what I've been looking for. I'm sure that my solution is not the most elegant or efficient, but I will settle for understanding how it works first before trying to squeeze the most performance out of it.
I found this question but this was similarly unhelpful: Dynamically adding elements to ArrayList in Groovy.
Edit: I'm trying to translate old company c-shell build scripts into Jenkins Pipelines. My initial string is an environment variable available on all our nodes that I also need to have available inside the Pipeline.
TL;DR - I need to be able to create an array from space separated values in a string, and then be able to loop over said array and each "element" be a complete string instead of a single char so that I can run pipeline steps properly.
回答1:
Try running this in your Jenkins script console (your.jenkins.url.yourcompany.com/script
):
def full_string = "/var/x /var/y /var/z"
def arr = full_string.split(" ")
for (i in arr) {
println "now got ${i}"
}
Result:
now got /var/x
now got /var/y
now got /var/z
来源:https://stackoverflow.com/questions/61146817/how-to-create-and-loop-over-an-arraylist-of-strings-in-jenkins-groovy-pipeline