Jenkinsfile $ {steps.env.BUILD_NUMBER}:替换错误

时间:2019-02-17 14:55:58

标签: jenkins groovy jenkins-pipeline

我正在尝试在詹金斯中打印一个变量。但是我收到一个错误消息,说“替代不好”。我正在使用Jenkinsfile来实现这一目标。这就是我在做什么。

static def printbn() {
    sh '''
            #!/usr/bin/env bash

            echo \"${env.BUILD_NUMBER}\"
    '''
}

pipeline {
    agent any
        stages {
            stage('Print Build Number') {
                steps {
                    printbn()
                }
            }
        }
}

我得到的错误

/var/lib/jenkins/workspace/groovymethod@tmp/durable-7d9ef0b0/script.sh: line 4: ${steps.env.BUILD_NUMBER}: bad substitution

注意:我正在使用Jenkins版本Jenkins ver. 2.163

1 个答案:

答案 0 :(得分:2)

在Shell中,不允许使用变量名.,这就是为什么出现以下错误的原因:bad substitution

在Groovy中,有四种表示字符串的方法:

  1. 单引号:“一个字符串”
  2. 三行单引号:“''字符串'''
  3. 双引号:“一个字符串”
  4. 三重双引号:“”“字符串”“”

并且Groovy仅对双引号和三重双引号字符串执行字符串插值。

例如:

def name = 'Tom'

print "Hello ${name}"
print """Hello ${name}"""  
// do interpolation before print, thus get Hello Tom printed out

print 'Hello ${name}' 
print '''Hello ${name}'''
//no interpolation thus, print Hello ${name} out directly.

BUILD_NUMBER是Jenkins job的内置环境变量。您可以直接在shell / bat中访问它。

static def printbn() {
    sh '''
    #!/usr/bin/env bash

    echo ${BUILD_NUMBER} 
    // directly access any Jenkins build-in environment variable,
    // no need to use pattern `env.xxxx` which only works in groovy not in shell/bat
    '''
}

如果要使用env.xxxx模式,则可以通过常规字符串插值将其存档。

static def printbn() {

    // use pipeline step: echo
    echo "${env.BUILD_NUMBER}" // env.BUILD_NUMBER is groovy variable 

    // or use pipeline step: sh
    sh """#!/usr/bin/env bash
      echo ${env.BUILD_NUMBER} 
    """
    // will do interpolation firstly, to replace ${env.BUILD_NUMBER} with real value
    // then execute the whole shell script.
}