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

Jenkins声明式管道中def列表结合for循环使用问题求助

问题解决:Groovy变量无法在Shell命令中读取

问题原因

你遇到的问题是单引号包裹的Shell命令不会解析Groovy变量。代码里sh 'the fruit name is ${x}'中的${x}会被Shell当作自身变量处理,但Shell环境中未定义该变量,因此输出为空。

解决方法

有两种可行的修改方式:

方式一:使用双引号包裹Shell命令

Groovy会优先解析双引号内的变量,替换变量值后再传递给Shell执行:

def data = [ "apple","orange" ]

stage('create sentence'){
    steps{
        script {
            for (x in data){
                sh "the fruit name is ${x}"
            }
        }
    }
}

方式二:字符串拼接

通过Groovy字符串拼接语法,将变量值直接拼入Shell命令字符串:

def data = [ "apple","orange" ]

stage('create sentence'){
    steps{
        script {
            for (x in data){
                sh 'the fruit name is ' + x
            }
        }
    }
}

两种方式都能得到预期输出:

  1. the fruit name is apple
  2. the fruit name is orange

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:30:58