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

如何在Jenkins中将Groovy数组传递给Shell脚本

解决Groovy数组传递给Shell脚本的问题

问题根源

你当前代码里,${templates}会被Groovy直接转换成[Temp1,Temp2,Temp3]这种字符串格式,Shell无法将其识别为数组,因此循环中${temp[i]}无法读取到正确的元素值。

修复代码示例

把Groovy数组转换成Shell可识别的数组格式,核心是将数组元素拼接为空格分隔的字符串,再在Shell中定义数组:

templates = ["Temp1","Temp2","Temp3"]
templateCount = templates.size()
sh """
  count=${templateCount} 
  temp=(${templates.join(" ")})
  for (( i=0; i < count; i++ ))
  do
    echo "Template Name = \${temp[i]}"
  done
"""

关键细节

  • 用templates.join(" ")把Groovy数组元素转为空格分隔的字符串,让Shell能正确解析为数组元素。
  • Shell中的变量引用要加反斜杠转义\${temp[i]},防止Groovy提前插值,确保由Shell自行处理变量。
  • 也可以用更简洁的Shell遍历方式,无需依赖长度计数:
templates = ["Temp1","Temp2","Temp3"]
sh """
  temp=(${templates.join(" ")})
  for name in "\${temp[@]}"
  do
    echo "Template Name = \$name"
  done
"""

特殊场景处理

如果数组元素包含空格、特殊字符(如@、#),需要给每个元素包裹双引号,避免Shell解析出错:

templates = ["Temp 1","Temp@2","Temp#3"]
sh """
  temp=(${templates.collect { "\"${it}\"" }.join(" ")})
  for name in "\${temp[@]}"
  do
    echo "Template Name = \$name"
  done
"""

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:35:20