如何将变量从Jenkinsfile传递给shell命令

Joe*_*Joe 16 shell groovy jenkins jenkins-pipeline jenkinsfile

我想使用我在Jenkinsfile脚本中使用的变量,然后将其值传递给shell脚本执行(作为环境变量或命令行参数).

但是以下内容Jenkinsfile:

for (i in [ 'a', 'b', 'c' ]) {
    echo i
    sh 'echo "from shell i=$i"'
}
Run Code Online (Sandbox Code Playgroud)

给出输出:

a
from shell i=
b
from shell i=
c
from shell i=
Run Code Online (Sandbox Code Playgroud)

期望的输出是这样的:

a
from shell i=a
b
from shell i=b
c
from shell i=c
Run Code Online (Sandbox Code Playgroud)

知道如何将值传递i给shell scipt吗?

编辑:根据马特的回答,我现在使用这个解决方案:

for (i in [ 'a', 'b', 'c' ]) {
    echo i
    sh "i=${i}; " + 'echo "from shell i=$i"'
}
Run Code Online (Sandbox Code Playgroud)

优点是,我不需要"在shell脚本中转义.

Mat*_*ard 21

您的代码使用文字字符串,因此您的Jenkins变量不会在shell命令中插入.你需要使用"在你的字符串里面插入你的变量sh.'只会传递一个文字字符串.所以我们需要在这里做一些改变.

首先是'改为":

for (i in [ 'a', 'b', 'c' ]) {
  echo i
  sh "echo "from shell i=$i""
}
Run Code Online (Sandbox Code Playgroud)

但是,现在我们需要逃避"内部:

for (i in [ 'a', 'b', 'c' ]) {
  echo i
  sh "echo \"from shell i=$i\""
}
Run Code Online (Sandbox Code Playgroud)

另外,如果一个变量直接附加到一个字符串,就像你在上面那样($ii=)上,我们需要用一些花括号将它关闭:

for (i in [ 'a', 'b', 'c' ]) {
  echo i
  sh "echo \"from shell i=${i}\""
}
Run Code Online (Sandbox Code Playgroud)

那会让你得到你想要的行为.


Tou*_*ick 13

扩展到Matts答案:对于多行sh脚本使用

sh """
  echo ${paramName}
"""
Run Code Online (Sandbox Code Playgroud)

代替

sh '''...'''
Run Code Online (Sandbox Code Playgroud)