如何将文本附加到 jenkinsfile 中的文件

How to append a text to a file in jenkinsfile

如何在 Jenkinsfile 注入 Jenkins BUILD_ID

中将文本附加到文件

我想看

version := "1.0.25"

其中 25 是 BUILD_ID

这是我的尝试

import hudson.EnvVars

node {

  stage('versioning'){
    echo 'retrieve build version'
    sh 'echo version := 1.0.${env.BUILD_ID} >> build.sbt'
  } 
}

错误:

version:=1.0.${env.BUILD_ID}: bad substitution

注意文件在当前目录

env.BUILD_ID 是一个 groovy 变量,而不是 shell 变量。由于您使用 single-quotes (') groovy 将 而不是 替换字符串中的变量并且 shell 不知道${env.BUILD_ID}。您需要使用 double-quotes " 并让 groovy 进行替换

sh "echo version := 1.0.${env.BUILD_ID} >> build.sbt"

或使用shell知道的变量

sh 'echo version := 1.0.$BUILD_ID >> build.sbt'

并且因为您需要用双引号括起来的版本,所以您需要这样的东西:

sh "echo version := \\"1.0.${env.BUILD_ID}\\" >> build.sbt"

writeFile内置的管道在这里也很有用,但需要一个读+写过程才能附加到文件。

def readContent = readFile 'build.sbt'
writeFile file: 'build.sbt', text: readContent+"\r\nversion := 1.0.${env.BUILD_ID}"

我使用肮脏的小包装函数来实现上面 Stefan Crain 的回答:

def appendFile(String fileName, String line) {
    def current = ""
    if (fileExists(fileName)) {
        current = readFile fileName
    }
    writeFile file: fileName, text: current + "\n" + line
}

我真的不喜欢它,但它确实有效,它通过斜线字符串绕过转义引号,例如:

def tempFile = '/tmp/temp.txt'
writeFile file: tempFile, text: "worthless line 1\n"
// now append the string 'version="1.2.3"  # added by appendFile\n' to tempFile
appendFile(tempFile,/version="1.2.3" # added by appendFile/ + "\n")