How to strip some form of new line character at end of parsed Jenkinsfile variable

Viewed 7567

I am wanting to pass variables between stages in a Jenkinsfile and am doing it as people suggest, by writing to a file then parsing it.

stage('1') {
  steps {
    sh "echo value > var.txt"
    script {
      VALUE = readFile('var.txt')
    }
  }
}

stage('2') {
  steps {
    sh "echo ${VALUE} && echo 'ok'"
  }
}

However, I am getting some form of new line character at the end of ${VALUE} that means I am trying to execute 2 lines and the && is causing the stage to barf. I've tried piping through tr -d '\r\n'but it doesn't seem to do anything.

2 Answers

I ran into this problem as well for my Jenkins file that is a groovy script, and this is what helped me get rid of the EOL / CR characters at the end of the value I wanted to use:

VALUE = readFile('var.txt').trim()

Other than doing a trim(), you can also make echo not add a new line after the value by specifying the -n parameter for it. So do sh "echo -n value > var.txt" instead.

Related