How to pass variables from Jenkinsfile to shell command

前端 未结 3 1894
庸人自扰
庸人自扰 2020-12-05 07:30

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 varia

相关标签:
3条回答
  • 2020-12-05 07:44

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

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

    instead of

    sh '''
      echo ${paramName}
    '''
    
    0 讨论(0)
  • 2020-12-05 07:51

    try this:

    for (i in [ 'a', 'b', 'c' ]) {
        echo i
        sh '''
        echo "from shell i=$i"
        '''
    }
    
    0 讨论(0)
  • 2020-12-05 08:05

    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.

    0 讨论(0)
提交回复
热议问题