QGA
QGA

Reputation: 3192

How to append a text to a file in jenkinsfile

How to append text to a file in a Jenkinsfile injecting the Jenkins BUILD_ID

I wish to see:

version := "1.0.25"

where 25 is the BUILD_ID

Here is my attempt:

import hudson.EnvVars

node {

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

Error:

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

Note the file is in the current directory

Upvotes: 26

Views: 81012

Answers (3)

TonyA
TonyA

Reputation: 71

I've used dirty little wrapper function to implement Stefan Crain's answer above:

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

I really don't like it, but it does the trick and it gets round escaping quotes via slashy strings,e.g.:

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")

Upvotes: 7

Stefan Crain
Stefan Crain

Reputation: 2060

The pipeline built in writeFile is also very useful here but requires a read+write process to append to a file.

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

Upvotes: 35

tkausl
tkausl

Reputation: 14269

env.BUILD_ID is a groovy variable, not a shell variable. Since you used single-quotes (') groovy will not substitute the variables in your string and the shell doesn't know about ${env.BUILD_ID}. You need to either use double-quotes " and let groovy do the substitution

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

or use the variable the shell knows

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

and since you need the version surrounded with doublequotes, you'd need something like this:

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

Upvotes: 22

Related Questions