How to receive local Git branch name with Jenkins Git plugin?

Viewed 103738

I am using Branch Specifier option of Jenkins Git plugin (v2.0) to run build on specific branch, e.g. 1.4.

${GIT_BRANCH} in this case contains origin/1.4 value.

How can I receive a name of the local Git branch used for cloning (i.e. just 1.4 without origin/ prefix?

I've tried Check out to specific local branch Additional Behaviour with branch name 1.4, but nothing had changed.

I've seen related PR on GitHub, but it was declined (as it fixes only one case with just origin remote).

13 Answers

@Chris answer helped me. Thank you!

Don't forget to add the "Additional Behavior -> Check out to specific local branch" under "Source Code Management".

enter image description here

Until I did not add that the ${GIT_LOCAL_BRANCH} variable was not availabe when I tried use it. (E.g.: execute shell command 'printenv' then check Console output)

After long time I finally got the solution for my case to get local git name (for SonarQube) without "origin/" in my Jenkins freestyle project (not Jenkinsfile). I am using Windows environment.

In Jenkins:

  • At "Source Code Management" section: add "Check out to specific local branch" and at "Branch name" enter: **
  • At "Build" section: I used and added "SonarScanner for MSBuild - Begin Analysis", where at "Additional arguments" I added: /d:sonar.branch.name=${GIT_LOCAL_BRANCH}

So only with this combination of ** and ${GIT_LOCAL_BRANCH} it worked for me.

No complex shell commands needed to achieve this, just add the below line :

branchFilter: 'origin.*/(.*)', in gitParameter as shown below

pipeline {
    agent any
    parameters {
        gitParameter branchFilter: 'origin.*/(.*)', defaultValue: 'master', name: 'BRANCH', type: 'PT_BRANCH'
    }
Related