Search code examples
jenkinsjenkins-pipeline

In the same Jenkinsfile stage, Why groovy script cannot access the file created in sh step?


Jenkinsfile:

pipeline {
agent any
stages {
    stage('Sec') {
        steps {
            sh '''#!/bin/bash
                set -e
                echo ${BUILD_NUMBER} > test_sec_fail.txt
                cat test_sec_fail.txt
            '''
            script {
                def fileExists = sh(script: 'test -e test_sec_fail.txt && echo "true" || echo "false"', returnStdout: true).trim()
                println "${fileExists}"
                def file = new File("test_sec_fail.txt")
                println(file.exists())
                println(file.canRead())
            }
        }
    }
}

}

Why the "fileExists" is true, but file.exists() and file.canRead() return false?


Solution

  • The shell command test executed within a sh step method checks for a file in the current workspace on the current agent. The same is true of the fileExists step method.

    The Groovy File class and its methods operate on the Jenkins master in a given directory. They should not be used without preparation in a Jenkins Pipeline for files in the current job workspace.