0
0
JenkinsHow-ToBeginner · 3 min read

How to Use readFile in Jenkins Pipeline

In Jenkins Pipeline, use the readFile step to read the contents of a file as a string. Simply call readFile('filename') inside your pipeline script to get the file content for further processing.
📐

Syntax

The readFile step reads the entire content of a file and returns it as a string. You provide the file path relative to the workspace.

  • readFile('filePath'): Reads the file at filePath.
  • The file path is relative to the Jenkins workspace directory.
  • The returned value is a string containing the file content.
groovy
def content = readFile('example.txt')
println(content)
💻

Example

This example shows a simple Jenkins Declarative Pipeline that reads a file named message.txt and prints its content to the console.

groovy
pipeline {
    agent any
    stages {
        stage('Read File') {
            steps {
                script {
                    def fileContent = readFile('message.txt')
                    echo "File content: ${fileContent}"
                }
            }
        }
    }
}
Output
File content: Hello from Jenkins Pipeline!
⚠️

Common Pitfalls

Common mistakes when using readFile include:

  • Trying to read a file that does not exist in the workspace, causing the pipeline to fail.
  • Using an absolute file path instead of a workspace-relative path.
  • Not wrapping readFile inside a script block in Declarative Pipelines.

Always ensure the file is checked out or created before reading it.

groovy
pipeline {
    agent any
    stages {
        stage('Wrong Usage') {
            steps {
                // This will fail if 'missing.txt' does not exist
                script {
                    def content = readFile('missing.txt')
                    echo content
                }
            }
        }
    }
}

// Correct usage requires the file to exist in the workspace before reading it.
📊

Quick Reference

readFile step summary:

UsageDescription
readFile('file.txt')Reads file content as a string
File pathRelative to workspace
Return typeString
Common errorFile not found if missing
UsageDescription
readFile('file.txt')Reads file content as a string
File pathRelative to workspace
Return typeString
Common errorFile not found if missing

Key Takeaways

Use readFile('filename') inside a script block to read file contents as a string.
File paths must be relative to the Jenkins workspace directory.
Ensure the file exists in the workspace before calling readFile to avoid errors.
readFile returns the entire file content as a single string.
Wrap readFile calls in script blocks when using Declarative Pipeline syntax.