How to Guard a Stage With fileExists in Jenkins
fileExists returns a boolean you can use in a when expression or if to gate work on a file being present.
Call fileExists('path') to test for a file in the workspace. Combine it with a when { expression { } } to skip a stage, or with an if in a script block for inline branching.
Steps
- Call
fileExists('path')where you need the boolean. - Use it in
when { expression { fileExists('...') } }to gate a stage. - Or branch with
if (fileExists('...'))inside ascriptblock.
Jenkinsfile
Jenkinsfile
pipeline {
agent any
stages {
stage('Migrate') {
when { expression { fileExists('db/migrations') } }
steps {
sh './run-migrations.sh'
}
}
stage('Build') {
steps {
script {
if (fileExists('yarn.lock')) { sh 'yarn install' }
else { sh 'npm ci' }
}
}
}
}
}Gotchas
- fileExists checks the current agent workspace, so run it after checkout.
- Paths are relative to the workspace root unless you give an absolute path.
Related guides
How to Capture the Exit Code and Output of sh in JenkinsCapture a shell command exit code with returnStatus and its output with returnStdout in a Jenkins pipeline, s…
How to Read a YAML or JSON Config in a Jenkins PipelineParse a YAML or JSON file from the workspace in a Jenkins pipeline with readYaml and readJSON from the Pipeli…