<p>There's a <a href="https://www.jenkins.io/doc/pipeline/steps/workflow-multibranch/#resolvescm-resolves-an-scm-from-an-scm-source-and-a-list-of-candidate-target-branch-names" rel="nofollow noreferrer"><code>resolveScm</code> step</a> implemented by the <a href="https://www.jenkins.io/doc/pipeline/steps/workflow-multibranch/" rel="nofollow noreferrer">Pipeline: Multibranch plugin</a>:</p>
<pre><code>checkout resolveScm(source: [$class: 'GitSCMSource',
                             credentialsId: '&lt;credentialsId&gt;',
                             id: '_',
                             remote: 'https://your.git.remote/repository.git',
                             traits: [[$class: 'jenkins.plugins.git.traits.BranchDiscoveryTrait']]],
                    targets: [BRANCH_NAME, 'master'])
</code></pre>
<p>Above procedure will look whether <code>$BRANCH_NAME</code> exists, check it out if yes and check out <code>master</code> otherwise.</p>

CC BY-SA 4.0
2019-10-23T15:09:02.850Z
This is not declarative but could be run in a script block. Declarative pipelines typically do not include a checkout function in a multibranch pipeline.
casey vega
CC BY-SA 4.0
2018-10-09T09:08:56.510Z
2020-09-14T11:53:54.260Z
2020-09-14T11:53:54.260Z
astriffe
<p>Sometimes it is easier to ask forgiveness than permission.</p>

<p>Instead of trying to figure out whether branch <code>b</code> exists, just try to check it out.  </p>

<p>If it fails, checkout branch <code>a</code>.</p>

<pre><code>script {
    try {
        checkout([
                $class: 'GitSCM',
                branches: [[name: 'b']],
                userRemoteConfigs: [[url: url]]
        ])
    }
    catch (Exception e) {
        checkout([
                $class: 'GitSCM',
                branches: [[name: 'a']],
                userRemoteConfigs: [[url: url]]
        ])
    }
}
</code></pre>

CC BY-SA 4.0
2019-12-23T15:30:36.483Z
Nice idea, but you will probably not get the expected result if the checkout fails for any reason other than the branch not existing...
Dan Cornilescu
CC BY-SA 4.0
2019-09-30T13:44:30.030Z
2019-09-30T13:44:30.030Z
cowlinator
<pre><code>pipeline {
  agent any 
  stages { 
    stage('Tests') {
      when {
        branch 'master'
      }
      steps {
        echo 'foo'
      } 
   }
}
</code></pre>

CC BY-SA 4.0
2018-10-16T06:59:59.200Z
2019-10-23T17:15:03.623Z
2019-10-23T17:15:03.623Z
Ram
<p>When using <a href="https://jenkins.io/doc/book/pipeline/jenkinsfile/" rel="nofollow noreferrer">Declarative Pipelines</a> you can achieve the goal of running some steps only for certain branches by using the <a href="https://jenkins.io/doc/book/pipeline/syntax/#when" rel="nofollow noreferrer">when directive</a> with the build-in condition <code>branch</code>:</p>
<blockquote>
<p><strong><code>branch</code></strong> Execute the stage when the branch being built matches the branch pattern (ANT style path glob) given, for example: when { branch 'master' }. Note that this only works on a multibranch Pipeline.</p>
</blockquote>
<pre class="lang-java prettyprint-override"><code>pipeline {
    agent any 
    stages { 
        stage(&quot;Build&quot;) {
            when { branch &quot;master&quot; }
            steps { 
               echo &quot;I am a master branch&quot;
            }
        }
    }
}
</code></pre>
<p>If you use Scripted Pipeline, you may also access the <code>BRANCH_NAME</code> from environment variable and do something with it:</p>
<pre class="lang-java prettyprint-override"><code>if (env.BRANCH_NAME == 'master') {
   //do something
}
</code></pre>
<p>Also have a look at <a href="https://jenkins.io/doc/book/pipeline/syntax/#flow-control" rel="nofollow noreferrer">Flow Control</a> to understand how you can control the flow of your pipeline.</p>

CC BY-SA 4.0
2022-07-18T13:24:49.217Z
`env.BRANCH_NAME` is not always available. Use `steps { sh 'printenv'}` to check.
Danijel
CC BY-SA 4.0
2019-10-23T05:35:26.730Z
2021-09-05T22:48:35.237Z
2021-09-05T22:48:35.237Z
papanito
<p>I'm currently trying to adopt my declarative pipeline in the following way:</p>

<p>I have multiple stages, some apply for all branches, some only for specific names.</p>

<p>What I'm now searching for is a way to get a when condition for the existance of a branch like this:</p>

<pre><code>if branch b exist
   checkout branch b
else
   checkout branch a
</code></pre>

<p>Sadly I haven't found a solution for it. I'm pretty sure there is a way using the <strong>git plugin</strong> though.</p>

<p>There's a <a href="https://stackoverflow.com/questions/19508326/jenkins-git-branch-selection-with-fallback/48579241#comment86569907_48579241">StackOverflow solution</a> for scripted pipelines, but I can't translate them though.</p>

<p>Can someone help me with this or point me at the right direction?</p>

<jenkins><jenkins-pipeline><jenkins-blueocean>
Jenkins declarative pipeline: use branch if it exist
Hoall
# Jenkins declarative pipeline: use branch if it exist

(Asked by: username_0 on 2018-04-12)

I'm currently trying to adopt my declarative pipeline in the following way:
I have multiple stages, some apply for all branches, some only for specific names.
What I'm now searching for is a way to get a when condition for the existance of a branch like this:
if branch b exist
   checkout branch b
else
   checkout branch a

Sadly I haven't found a solution for it. I'm pretty sure there is a way using the git plugin though.
There's a StackOverflow solution for scripted pipelines, but I can't translate them though.
Can someone help me with this or point me at the right direction?

**Tags:** jenkins, jenkins-pipeline, jenkins-blueocean


---

## 4 answers

### Answer by username_6 on 2019-10-23. Score: 4 | Accepted answer

When using Declarative Pipelines you can achieve the goal of running some steps only for certain branches by using the when directive with the build-in condition branch:

branch Execute the stage when the branch being built matches the branch pattern (ANT style path glob) given, for example: when { branch 'master' }. Note that this only works on a multibranch Pipeline.

pipeline {
    agent any 
    stages { 
        stage("Build") {
            when { branch "master" }
            steps { 
               echo "I am a master branch"
            }
        }
    }
}

If you use Scripted Pipeline, you may also access the BRANCH_NAME from environment variable and do something with it:
if (env.BRANCH_NAME == 'master') {
   //do something
}

Also have a look at Flow Control to understand how you can control the flow of your pipeline.

> **Comments:**
> **username_7**: `env.BRANCH_NAME` is not always available. Use `steps { sh 'printenv'}` to check.  

---

### Answer by username_1 on 2018-10-09. Score: 5

There's a resolveScm step implemented by the Pipeline: Multibranch plugin:
checkout resolveScm(source: [$class: 'GitSCMSource',
                             credentialsId: '',
                             id: '_',
                             remote: 'https://your.git.remote/repository.git',
                             traits: [[$class: 'jenkins.plugins.git.traits.BranchDiscoveryTrait']]],
                    targets: [BRANCH_NAME, 'master'])

Above procedure will look whether $BRANCH_NAME exists, check it out if yes and check out master otherwise.

> **Comments:**
> **username_2**: This is not declarative but could be run in a script block. Declarative pipelines typically do not include a checkout function in a multibranch pipeline.  

---

### Answer by username_3 on 2019-09-30. Score: 2

Sometimes it is easier to ask forgiveness than permission.
Instead of trying to figure out whether branch b exists, just try to check it out.  
If it fails, checkout branch a.
script {
    try {
        checkout([
                $class: 'GitSCM',
                branches: [[name: 'b']],
                userRemoteConfigs: [[url: url]]
        ])
    }
    catch (Exception e) {
        checkout([
                $class: 'GitSCM',
                branches: [[name: 'a']],
                userRemoteConfigs: [[url: url]]
        ])
    }
}

> **Comments:**
> **username_4**: Nice idea, but you will probably not get the expected result if the checkout fails for any reason other than the branch not existing...  

---

### Answer by username_5 on 2018-10-16. Score: 1

pipeline {
  agent any 
  stages { 
    stage('Tests') {
      when {
        branch 'master'
      }
      steps {
        echo 'foo'
      } 
   }
}


---

