Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/66063558/jenkins-pipeline-push-string-to-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}"
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...