Answers: <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>
  
Answers: CC BY-SA 4.0
Answers: 2019-10-23T15:09:02.850Z
Answers: 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.
Answers: casey vega
Answers: CC BY-SA 4.0
Answers: 2018-10-09T09:08:56.510Z
Answers: 2020-09-14T11:53:54.260Z
Answers: 2020-09-14T11:53:54.260Z
Answers: astriffe
Answers: <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>
  
Answers: CC BY-SA 4.0
Answers: 2019-12-23T15:30:36.483Z
Answers: Nice idea, but you will probably not get the expected result if the checkout fails for any reason other than the branch not existing...
Answers: Dan Cornilescu
Answers: CC BY-SA 4.0
Answers: 2019-09-30T13:44:30.030Z
Answers: 2019-09-30T13:44:30.030Z
Answers: cowlinator
Answers: <pre><code>pipeline {
    agent any 
    stages { 
      stage('Tests') {
        when {
          branch 'master'
        }
        steps {
          echo 'foo'
        } 
     }
  }
  </code></pre>
  
Answers: CC BY-SA 4.0
Answers: 2018-10-16T06:59:59.200Z
Answers: 2019-10-23T17:15:03.623Z
Answers: 2019-10-23T17:15:03.623Z
Answers: Ram
Answers: <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>
  
Answers: CC BY-SA 4.0
Answers: 2022-07-18T13:24:49.217Z
Answers: `env.BRANCH_NAME` is not always available. Use `steps { sh 'printenv'}` to check.
Answers: Danijel
Answers: CC BY-SA 4.0
Answers: 2019-10-23T05:35:26.730Z
Answers: 2021-09-05T22:48:35.237Z
Answers: 2021-09-05T22:48:35.237Z
Answers: papanito
Body: <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>
  
Tags: <jenkins><jenkins-pipeline><jenkins-blueocean>
Title: Jenkins declarative pipeline: use branch if it exist
UserDisplayName: Hoall
ThreadText: # 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](https://stackoverflow.com/questions/19508326/jenkins-git-branch-selection-with-fallback/48579241#comment86569907_48579241) 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](https://jenkins.io/doc/book/pipeline/jenkinsfile/) you can achieve the goal of running some steps only for certain branches by using the [when directive](https://jenkins.io/doc/book/pipeline/syntax/#when) 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.
  
  ```java
  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:
  
  ```java
  if (env.BRANCH_NAME == 'master') {
     //do something
  }
  
  ```
  
  Also have a look at [Flow Control](https://jenkins.io/doc/book/pipeline/syntax/#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](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) implemented by the [Pipeline: Multibranch plugin](https://www.jenkins.io/doc/pipeline/steps/workflow-multibranch/):
  
  ```
  checkout resolveScm(source: [$class: 'GitSCMSource',
                               credentialsId: '<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'
        } 
     }
  }
  
  ```
  
  
  ---
  
  