Search code examples
jenkinsjenkins-pipelinedeclarativeunexpected-token

Failed to assign sh output to a variable when sh output contains opening bracket ( | Jenkins Declarative Pipeline


I am trying in one of the steps to write some data in file, and in step after that to read that data using and assign it to a variable. This is my declarative Jenkins pipeline:


pipeline {
    agent {label 'build-slave-aws'} 
    stages {
        stage('Notify about start') {
            steps {
                sh 'echo "Some fatct with brackets ()" > /tmp/facts.issues'           
            }
        }

         stage('Gather the facts') { 
            steps {
                    script {
                        factsIssues = sh( script: "cat /tmp/facts.issues", returnStdout: true )
                    }

                   sh "echo these are facts: ${factsIssues}"     
            }
        }
    }
}

The output of this run is following:

Started by user 123
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on i-000df827977fd5175 in /workspace/workspace/test
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Notify about start)
[Pipeline] sh
+ echo 'Some fatct with brackets ()'
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Gather the facts)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ cat /tmp/facts.issues
[Pipeline] }
[Pipeline] // script
[Pipeline] sh
/workspace/workspace/test@tmp/durable-2a1f8cdf/script.sh: line 1: syntax error near unexpected token `('
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 2
Finished: FAILURE

Any other text that doesn't contain ( simply work just fine. Do you have any suggestion on how I can write some data in file with ( and reading that back to a variable?


Solution

  • You are missing quotes around the argument of the echo command within the last sh script.

    Fix:

    sh "echo 'these are facts: ${factsIssues}'"