[git] Get git branch name in Jenkins Pipeline/Jenkinsfile

I've create a jenkins pipeline and it is pulling the pipeline script from scm.
I set the branch specifier to 'all', so it builds on any change to any branch.

How do I access the branch name causing this build from the Jenkinsfile?

Everything I have tried echos out null except

sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()

which is always master.

This question is related to git jenkins branch jenkins-pipeline

The answer is


This is for simple Pipeline type - not multibranch. Using Jenkins 2.150.1

environment { FULL_PATH_BRANCH = "${sh(script:'git name-rev --name-only HEAD', returnStdout: true)}" GIT_BRANCH = FULL_PATH_BRANCH.substring(FULL_PATH_BRANCH.lastIndexOf('/') + 1, FULL_PATH_BRANCH.length()) }

then use it env.GIT_BRANCH


For me this worked: (using Jenkins 2.150, using simple Pipeline type - not multibranch, my branch specifier: '**')

echo 'Pulling... ' + env.GIT_BRANCH

Output:

Pulling... origin/myBranch

where myBranch is the name of the feature branch


A colleague told me to use scm.branches[0].name and it worked. I wrapped it to a function in my Jenkinsfile:

def getGitBranchName() {
    return scm.branches[0].name
}

Use multibranch pipeline job type, not the plain pipeline job type. The multibranch pipeline jobs do posess the environment variable env.BRANCH_NAME which describes the branch.

In my script..

stage('Build') {
    node {
        echo 'Pulling...' + env.BRANCH_NAME
        checkout scm
        
    }
}

Yields...

Pulling...master

For pipeline:

pipeline {
  environment {
     BRANCH_NAME = "${GIT_BRANCH.split("/")[1]}"
  }
}

FWIW the only thing that worked for me in PR builds was ${CHANGE_BRANCH}

(may not work on master, haven't seen that yet)


Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.


Just getting the name from scm.branches is not enough if you've used a build parameter as a branch specifier, e.g. ${BRANCH}. You need to expand that string into a real name:

scm.branches.first().getExpandedName(env.getEnvironment())

Note that getEnvironment() must be an explicit getter otherwise env will look up for an environment variable called environment.

Don't forget that you need to approve those methods to make them accessible from the sandbox.


Examples related to git

Does the target directory for a git clone have to match the repo name? Git fatal: protocol 'https' is not supported Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) git clone: Authentication failed for <URL> destination path already exists and is not an empty directory SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 GitLab remote: HTTP Basic: Access denied and fatal Authentication How can I switch to another branch in git? VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio?

Examples related to jenkins

Maven dependencies are failing with a 501 error Jenkins pipeline how to change to another folder Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding How to solve npm install throwing fsevents warning on non-MAC OS? Run bash command on jenkins pipeline Try-catch block in Jenkins pipeline script How to print a Groovy variable in Jenkins? Jenkins pipeline if else not working Error "The input device is not a TTY"

Examples related to branch

Get git branch name in Jenkins Pipeline/Jenkinsfile Why do I have to "git push --set-upstream origin <branch>"? Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.? When does Git refresh the list of remote branches? Fix GitLab error: "you are not allowed to push code to protected branches on this project"? Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository." Git: Merge a Remote branch locally git pull from master into the development branch Depend on a branch or tag using a git URL in a package.json? How can I copy the content of a branch to a new local branch?

Examples related to jenkins-pipeline

Jenkins pipeline how to change to another folder Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock Try-catch block in Jenkins pipeline script How to print a Groovy variable in Jenkins? Error "The input device is not a TTY" How to set and reference a variable in a Jenkinsfile Get git branch name in Jenkins Pipeline/Jenkinsfile Jenkins: Can comments be added to a Jenkinsfile? How to define and use function inside Jenkins Pipeline config? Environment variable in Jenkins Pipeline