Search code examples
jenkinsjenkins-pipelinejenkins-groovyjenkins-cli

How can I concatenate variables in Jenkins file


I have a Jenkinsfile which I want to load variables into from a file during execution of the build, I also want to concatenate the variable into one line and print it out.

pipeline {
    agent any
    stages {
        stage("foo") {
            steps {
                script {
                    env.name = readFile 'name.txt' 
                    env.tag = readFile 'tag.txt'
                }
                echo "${env.name}:${env.tag}"
            }
        }
    }
}

name.txt contains Uzodimma
path.txt contains latest

When I run the pipeline, I get
Uzodimma
:latest

I expected
Uzodimma:latest

Is there a way I can do this in Jenkinsfile?


Solution

  • The issue here is that your files have newline characters in them, so they are assigned to your variables as part of the String. You can remove the newlines with the trim method since readFile returns a String:

    env.name = readFile('name.txt').trim()
    env.tag = readFile('tag.txt').trim()
    

    and the returned standard out will be as you expect.