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 } } } }
两种方式都能得到预期输出:
- the fruit name is apple
- the fruit name is orange
内容的提问来源于stack exchange,提问作者Gopal
相关产品推荐
相关产品推荐

