jenkinsjenkins-pipelinejenkins-groovy

Jenkins read the content of a file to a variable


i am adding a parameter to jenkins parameter type stashed file. When i do a cat that works fine but if i want to save the file contents to a variable it fails

   echo "File check..."
                script {
                     unstash 'testFile1'
                    sh 'cat testFile1'
                    echo "This works"
                    content_file = readFile "testFile1"
                    echo $content_file
                }

Error

jenkinsci.plugins.workflow.actions.ErrorAction$ErrorId: 
groovy.lang.MissingPropertyException: No such property: $content_file for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)

Is there a way to read the file contents to a variable ?


Solution

  • Jenkins DSL is based on Groovy and in Groovy, unlike bash, you don't need to add $ to reference a variable:

       echo "File check..."
                    script {
                         unstash 'testFile1'
                        sh 'cat testFile1'
                        echo "This works"
                        content_file = readFile "testFile1"
                        echo content_file
                    }