如何将变量从Jenkinsfile传递给shell命令 [英] How to pass variables from Jenkinsfile to shell command

查看:602
本文介绍了如何将变量从Jenkinsfile传递给shell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

但是以下 Jenkinsfile



< pre $ 对于(我在['a','b','c']){
echo'
sh'echo'from shell i = $ i '
}

给出结果:

  a shell中的
i =
b中的
i中的
c
i =

所需的输出如下所示:

  a shell中的
i = shell中的
b
i = b $ bc中的b
中的b $ b = b $ b

任何想法如何将 i 的值传递给shell scipt?



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



<$ (我在['a','b','c']){
echo i
shi = $ {i}; + echofrom shell i = $ i'
}

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

解决方案

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



第一个是将 ' to

  for我在['a','b','c']){
回声我
shshell的回声i = $ i
}

然而,现在我们需要在内部转义

  for(i in ['a','b','c']){
echo i
shecho \from shell i = $ i \
}



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

  for(i in ['a','b' ,'c']){
echo i
shecho \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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆