Check if a file exists in jenkins pipeline

Solution 1:

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:

The keyword "return" must be used

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