Search code examples
arraysjenkinsjenkins-pipeline

jenkins pipeline push string to array


I have a script in Jenkins:

stage('test') {
    steps {
        script {
            def listCatalog = sh script: "ls src/examplecatalog", returnStdout: true
            def arrayExample=[]
            arrayExample+=("$listCatalog")
            echo "${arrayExample}"
        }
    }
}

arrayExample returned [catalog_1 catalog_2 catalog_3] but it's not array I think it's string. I need array like this: ['catalog_1', 'catalog_2', 'catalog_3'].

How I can push/append string to empty array in Jenkins?


Solution

  • The sh Jenkins DSL will return a string, that you have to convert to an array by using split() from groovy String class api like below

    node {
        //creating some folder structure for demo
        sh "mkdir -p a/b a/c a/d"
        
        def listOfFolder = sh script: "ls $WORKSPACE/a", returnStdout: true
    
        def myArray=[]
        listOfFolder.split().each { 
            myArray << it
        }
        
        print myArray
        print myArray.size()
    }
    

    and the result will be

    enter image description here

    In the example, I have used one way to add an element to an array but there are many ways you can add an element to an array like this

    so on your example, it will be

    stage('test') {
        steps {
            script {
                def listCatalog = sh script: "ls src/examplecatalog", returnStdout: true
                def arrayExample=[]
                listCatalog.split().each {
                  arrayExample << it
                }
                echo "${arrayExample}"
            }
        }
    }