You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins Pipeline中如何按索引匹配参数值输出对应内容?

Jenkins Pipeline 索引匹配输出修正

问题说明

原Pipeline脚本使用嵌套循环,导致每个动物依次匹配所有数字行,输出笛卡尔积结果。需要实现按索引一一对应输出:cat One 2、dog Two 3、horse Three 4,同时解决曾出现的逐个字符输出问题。

原脚本

pipeline {
    agent any
    
    parameters {
        
        text(name: 'NUMBER_TEXT', defaultValue: 'One 2\nTwo 3\nThree 4\n', description: '')
        string(name: 'ANIMAL_TEXT', defaultValue: 'cat dog horse', description: '')
    }
    stages {
        stage("Environnement variables") {
            steps {
                script{
                    def numbers="${params.NUMBER_TEXT}".split("\r?\n")
                    def animals="${params.ANIMAL_TEXT}".split(" ")

                    for (animal in animals) {
                        for (number in numbers) {
                            echo "**VM2** $animal"
                            echo "**VM** $number"
                        }
                    }
                }
            }
        }
    }
}

修正后脚本

pipeline {
    agent any
    
    parameters {
        text(name: 'NUMBER_TEXT', defaultValue: 'One 2\nTwo 3\nThree 4\n', description: '')
        string(name: 'ANIMAL_TEXT', defaultValue: 'cat dog horse', description: '')
    }
    stages {
        stage("Environnement variables") {
            steps {
                script{
                    // 分割数字文本并过滤空行(处理末尾换行产生的空元素)
                    def numbers = params.NUMBER_TEXT.split("\r?\n").findAll { it.trim() != '' }
                    // 分割动物文本
                    def animals = params.ANIMAL_TEXT.split(" ")
                    
                    // 遍历索引,取两个数组的最小长度避免越界
                    def maxIndex = Math.min(numbers.size(), animals.size()) - 1
                    for (int i = 0; i <= maxIndex; i++) {
                        def animal = animals[i]
                        def number = numbers[i]
                        echo "**VM2** $animal"
                        echo "**VM** $number"
                    }
                }
            }
        }
    }
}

修正说明

  1. 移除嵌套循环:原嵌套循环会生成笛卡尔积,改为按索引遍历,实现一一对应
  2. 过滤空元素:对numbers数组做过滤,处理NUMBER_TEXT末尾换行导致的空字符串,避免匹配空内容
  3. 索引安全处理:取两个数组的最小长度遍历,防止其中一个数组长度不足导致索引越界
  4. 避免逐个字符输出:确保split操作正确分割数组,避免误将字符串直接作为数组迭代(逐个字符输出问题通常由此引发)

期望输出

[Pipeline] echo
**VM2** cat
[Pipeline] echo
**VM** One 2
[Pipeline] echo
**VM2** dog
[Pipeline] echo
**VM** Two 3
[Pipeline] echo
**VM2** horse
[Pipeline] echo
**VM** Three 4
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

内容的提问来源于stack exchange,提问作者anew10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 12:34:52