Skip to content
Latchkey

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 a script block.

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

Run this faster and cheaper on Latchkey managed runners. Start free →