How to pass variables from Jenkinsfile to shell command

点点圈 提交于 2019-11-27 22:55:55

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.

Extension to Matts answer: For multi-line sh scripts use

sh """
  echo ${paramName}
"""

instead of

sh '''...'''

try this:

for (i in [ 'a', 'b', 'c' ]) {
    echo i
    sh '''
    echo "from shell i=$i"
    '''
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!