0

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?

1 Answer 1

2

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}"
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.