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

use*_*894 4 groovy jenkins jenkins-pipeline

我正在尝试在 Jenkins 中打印一个变量。但是我收到一条错误消息,说“替换不当”。我正在使用 Jenkinsfile 来实现这一点。这就是我正在做的。

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

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

pipeline {
    agent any
        stages {
            stage('Print Build Number') {
                steps {
                    printbn()
                }
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误

/var/lib/jenkins/workspace/groovymethod@tmp/durable-7d9ef0b0/script.sh: line 4: ${steps.env.BUILD_NUMBER}: bad substitution
Run Code Online (Sandbox Code Playgroud)

注意:我使用的是 Jenkins 版本 Jenkins ver. 2.163

yon*_*ong 20

在 Shell 中,不允许使用变量名.,这就是为什么您会收到以下错误:bad substitution

在 Groovy 中,有 4 种表示字符串的方式:

  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.
Run Code Online (Sandbox Code Playgroud)

BUILD_NUMBER是 Jenkins 工作的内置环境变量。你可以直接在 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
    '''
}
Run Code Online (Sandbox Code Playgroud)

如果您想使用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.
}
Run Code Online (Sandbox Code Playgroud)