How to Run a Stage Only on a Branch Pattern in a Jenkins Pipeline
The when { branch } condition gates a stage to matching branches using a glob or regex comparator.
Use when { branch pattern: ..., comparator: ... } to run a stage only on matching branches. Combine patterns with anyOf for several allowed branches.
Gate a stage to release branches
The deploy stage runs only on main or any release/* branch via a regex comparator.
Jenkinsfile
pipeline {
agent any
stages {
stage('Deploy') {
when {
anyOf {
branch 'main'
branch pattern: 'release/.*', comparator: 'REGEXP'
}
}
steps {
sh './deploy.sh'
}
}
}
}Gotchas
env.BRANCH_NAMEis only populated in multibranch pipelines; in a plain pipeline jobwhen { branch }has nothing to match.- The default comparator is GLOB; set
comparator: 'REGEXP'for real regex patterns. - Use
anyOf/allOfto combine multiple branch patterns or mix with otherwhenconditions.
Related guides
How to Run a Job Only on a Branch Pattern in CircleCIRun a CircleCI job only on matching branches with filters:branches:only and a regex, plus ignore patterns to…
How to Conditionally Run a Stage in a Jenkins PipelineConditionally run a Jenkins stage with the when directive - branch, environment, expression, and changeset co…