Check if a file exists in jenkins pipeline

JenkinsJenkins Pipeline

Jenkins Problem Overview


I am trying to run a block if a directory exists in my jenkins workspace and the pipeline step "fileExists: Verify file exists" in workspace doesn't seem to work correctly.

I'm using Jenkins v 1.642 and Pipeline v 2.1. and trying to have a condition like

if ( fileExists 'test1' ) {
  //Some block
}

What are the other alternatives I have within the pipeline?

Jenkins Solutions


Solution 1 - Jenkins

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

Solution 2 - Jenkins

The keyword "return" must be used

stage('some stage') {
    when { expression { return fileExists ('myfile') } }
    steps {
           echo "file exists"
          }
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBalualwaysView Question on Stackoverflow
Solution 1 - JenkinsGergely TothView Answer on Stackoverflow
Solution 2 - JenkinsRomanView Answer on Stackoverflow