如何将变量从 Jenkinsfile 传递到 shell 命令 [英] How to pass variables from Jenkinsfile to shell command
问题描述
我想使用我在 Jenkinsfile
脚本中使用的变量,然后将其值传递给 shell 脚本执行(作为环境变量或命令行参数).
I want to use a variable which I am using inside of my Jenkinsfile
script, and then pass its value into a shell script execution (either as an environment variable or command line parameter).
但是下面的Jenkinsfile
:
for (i in [ 'a', 'b', 'c' ]) {
echo i
sh 'echo "from shell i=$i"'
}
给出输出:
a
from shell i=
b
from shell i=
c
from shell i=
所需的输出类似于:
a
from shell i=a
b
from shell i=b
c
from shell i=c
知道如何将 i
的值传递给 shell scipt 吗?
Any idea how to pass the value of i
to the shell scipt?
基于 Matt 的回答,我现在使用这个解决方案:
Based upon Matt's answer, I now use this solution:
for (i in [ 'a', 'b', 'c' ]) {
echo i
sh "i=${i}; " + 'echo "from shell i=$i"'
}
优点是我不需要在shell脚本中转义"
.
The advantage is, that I don't need to escape the "
in the shell script.
推荐答案
您的代码使用的是文字字符串,因此您的 Jenkins 变量不会被插入到 shell 命令中.您需要使用 "
将变量插入到 sh
内的字符串中.'
只会传递一个文字字符串.所以我们需要这里有一些变化.
Your code is using a literal string and therefore your Jenkins variable will not be interpolated inside the shell command. You need to use "
to interpolate your variable inside your strings inside the sh
. '
will just pass a literal string. So we need to make a few changes here.
首先是将'
改为"
:
for (i in [ 'a', 'b', 'c' ]) {
echo i
sh "echo "from shell i=$i""
}
不过,现在我们需要对里面的"
进行转义:
However, now we need to escape the "
on the inside:
for (i in [ 'a', 'b', 'c' ]) {
echo i
sh "echo "from shell i=$i""
}
此外,如果变量像您在上面所做的那样直接附加到字符串($i
到 i=
),我们需要用一些来关闭它花括号:
Additionally, if a variable is being appended directly to a string like you are doing above ($i
onto i=
), we need to close it off with some curly braces:
for (i in [ 'a', 'b', 'c' ]) {
echo i
sh "echo "from shell i=${i}""
}
这会让你得到你想要的行为.
That will get you the behavior you desire.
这篇关于如何将变量从 Jenkinsfile 传递到 shell 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!