首页 > 解决方案 > 詹金斯管道将字符串推送到数组

问题描述

我在詹金斯有一个脚本:

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

arrayExample返回[catalog_1 catalog_2 catalog_3]但它不是数组我认为它是字符串。我需要这样的数组: ['catalog_1', 'catalog_2', 'catalog_3'].

如何在 Jenkins 中将字符串推送/附加到空数组?

标签: arraysjenkinsjenkins-pipeline

解决方案


Jenkins DSL将返回一个字符串,您必须使用来自 groovy String 类 apish的 split() 将其转换为数组,如下所示

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()
}

结果将是

在此处输入图像描述

在示例中,我使用了一种方法将元素添加到数组中,但是您可以通过多种方法将元素添加到数组中,如下所示

所以在你的例子中,它将是

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

推荐阅读