How to append a text to a file in jenkinsfile

て烟熏妆下的殇ゞ 提交于 2019-12-22 04:01:10

问题


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

I wish to see

version := "1.0.25"

where 25 is 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


回答1:


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"



回答2:


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



回答3:


You can write to a file with the help of sh step as below

def output= ‘version := “1.0.’+BUILD_ID+’”’
sh script: “echo ${output} >> file.txt”


来源:https://stackoverflow.com/questions/41900830/how-to-append-a-text-to-a-file-in-jenkinsfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!