Search code examples
jenkinsjenkins-pipelinejenkins-groovyjenkins-declarative-pipeline

How to handle wildcards in `fileExists()` function without Plugins in Jenkins


I am using Jenkins declarative pipeline syntax and I need to check if a file exists. Otherwise it should abort the current stage. The problem I encounter is that the file contains a timestamp which is different every time the build process runs.

I have found this thread. But sadly they use a plugin I dont have access to, so it does not fit my problem.

Here is what I have so far:

    stage('Check if file exists') {
        steps {
            script {
                if(fileExists('./path/to/file/name_1234567890.tar.gz')) {
                    currentBuild.result = "ABORTED"
                    error('Could not find file!')
                }
            }
        }
    }

Thanks in advance.


Solution

  • Use findFiles which allows glob syntax:

    stage('Check if file exists') {
            steps {
                script {
                    def any_files = false
                    def output_files = findFiles glob: './path/to/file/name_*.tar.gz'
                    for (def one_file in output_files) { any_files = true; break }
                    if (any_files) { // or maybe (!any_files) 
                        currentBuild.result = "ABORTED"
                        error('Could not find file!')
                    }
                }
            }
        }