如何将变量从 Jenkinsfile 传递给 shell 命令 [英] How to pass variables from Jenkinsfile to shell command
问题描述
我想使用我在 Jenkinsfile
脚本中使用的变量,然后将其值传递给 shell 脚本执行(作为环境变量或命令行参数).>
但是下面的Jenkinsfile
:
for (i in [ 'a', 'b', 'c' ]) {回声我sh 'echo "from shell i=$i"'}
给出输出:
a从壳 i=乙从壳 i=C从壳 i=
所需的输出类似于:
a从壳 i=a乙从壳 i=bC从壳 i=c
知道如何将 i
的值传递给 shell scipt 吗?
根据马特的回答,我现在使用这个解决方案:
for (i in [ 'a', 'b', 'c' ]) {回声我sh "i=${i}; " + 'echo "from shell i=$i"'}
优点是,我不需要转义 shell 脚本中的 "
.
您的代码正在使用文字字符串,因此您的 Jenkins 变量不会被插入到 shell 命令中.您需要使用 "
在 sh
内的字符串中插入变量.'
只会传递一个文字字符串.所以我们需要制作这里有一些变化.
首先是将'
改为"
:
for (i in [ 'a', 'b', 'c' ]) {回声我sh "echo "from shell i=$i""}
然而,现在我们需要转义里面的"
:
for (i in [ 'a', 'b', 'c' ]) {回声我sh "echo "from shell i=$i""}
此外,如果一个变量像你上面所做的那样直接附加到一个字符串($i
到 i=
),我们需要用一些来关闭它花括号:
for (i in [ 'a', 'b', 'c' ]) {回声我sh "echo "from shell i=${i}""}
这会让你得到你想要的行为.
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).
But the following Jenkinsfile
:
for (i in [ 'a', 'b', 'c' ]) {
echo i
sh 'echo "from shell i=$i"'
}
Gives the output:
a
from shell i=
b
from shell i=
c
from shell i=
Desired output is something like:
a
from shell i=a
b
from shell i=b
c
from shell i=c
Any idea how to pass the value of i
to the shell scipt?
Edit: 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"'
}
The advantage is, that I don't need to escape the "
in the shell script.
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.
The first is to change the '
to "
:
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""
}
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屋!