Skip to content

Instantly share code, notes, and snippets.

@oifland
Last active March 23, 2024 17:59
Show Gist options
  • Save oifland/ab56226d5f0375103141b5fbd7807398 to your computer and use it in GitHub Desktop.
Save oifland/ab56226d5f0375103141b5fbd7807398 to your computer and use it in GitHub Desktop.
Loops in Jenkinsfiles
// Related to https://issues.jenkins-ci.org/browse/JENKINS-26481
abcs = ['a', 'b', 'c']
node('master') {
stage('Test 1: loop of echo statements') {
echo_all(abcs)
}
stage('Test 2: loop of sh commands') {
loop_of_sh(abcs)
}
stage('Test 3: loop with preceding SH') {
loop_with_preceding_sh(abcs)
}
stage('Test 4: traditional for loop') {
traditional_int_for_loop(abcs)
}
}
@NonCPS // has to be NonCPS or the build breaks on the call to .each
def echo_all(list) {
list.each { item ->
echo "Hello ${item}"
}
}
// outputs all items as expected
@NonCPS
def loop_of_sh(list) {
list.each { item ->
sh "echo Hello ${item}"
}
}
// outputs only the first item
@NonCPS
def loop_with_preceding_sh(list) {
sh "echo Going to echo a list"
list.each { item ->
sh "echo Hello ${item}"
}
}
// outputs only the "Going to echo a list" bit
//No NonCPS required
def traditional_int_for_loop(list) {
sh "echo Going to echo a list"
for (int i = 0; i < list.size(); i++) {
sh "echo Hello ${list[i]}"
}
}
// echoes everything as expected
@vinodkumar4b9
Copy link

Hi @abgm,

I have tried your script and Its working fine , But Instead of passing values in an array as you did , How can I read them from a file and print them .

@vinodkumar4b9
Copy link

Hi All,

Actually I wanted to read files from Text file and wanted to Iterate the same in for loop and print values one by one , Any Suggestions on this is highly appreciated as I have spend so much time on this , But still couldnt find out , I an able to read the values but not able to print them using for loop

Sharing the code below for refernce

pipeline {
agent any
stages {
stage('Example') {
steps {

            script {
                def browsers =   readFile(file: 'repos.txt') 
                def lines = browsers.readLines()
                
                for (int i = 0; i < lines.size(); ++i) {
                    
                    echo "${lines}"
                }
            }
        }
    }
}

}

getting different outputs lets say getting all values at a time five times as size of file is five words , But I need one by one only one at a time in for loop

@sebastianarca
Copy link

Very preatty :D

@guna799
Copy link

guna799 commented Dec 28, 2022

Thanks, looking for the same .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment