[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


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

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
}

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


For pipeline:

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

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.


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


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

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


Questions with git tag:

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? How to know the git username and email saved during configuration? How to add a new project to Github using VS Code git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054 fatal: ambiguous argument 'origin': unknown revision or path not in the working tree HTTP Basic: Access denied fatal: Authentication failed npm notice created a lockfile as package-lock.json. You should commit this file Do I commit the package-lock.json file created by npm 5? Abort a Git Merge key_load_public: invalid format git - remote add origin vs remote set-url origin Visual Studio 2017 - Git failed with a fatal error Get git branch name in Jenkins Pipeline/Jenkinsfile Changing the git user inside Visual Studio Code How to compare different branches in Visual Studio Code Git checkout - switching back to HEAD Clear git local cache Deleting a local branch with Git Rebuild Docker container on file changes Cloning specific branch How to add chmod permissions to file in Git? Git copy changes from one branch to another Git merge with force overwrite Project vs Repository in GitHub How to add a file to the last commit in git? Getting permission denied (public key) on gitlab Delete commit on gitlab gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0] Remove a modified file from pull request Updates were rejected because the tip of your current branch is behind its remote counterpart Can't push to the heroku How to discard local changes and pull latest from GitHub repository In Visual Studio Code How do I merge between two local branches? error: RPC failed; curl transfer closed with outstanding read data remaining Change drive in git bash for windows Checkout Jenkins Pipeline Git SCM with credentials? How to fix git error: RPC failed; curl 56 GnuTLS Trying to pull files from my Github repository: "refusing to merge unrelated histories" Visual Studio Code how to resolve merge conflicts with git? merge one local branch into another local branch Can't push to remote branch, cannot be resolved to branch

Questions with jenkins tag:

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" 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 Rebuild Docker container on file changes How to use the curl command in PowerShell? Jenkins: Cannot define variable in pipeline stage Jenkins fails when running "service start jenkins" How to reset the use/password of jenkins on windows? How can I remove jenkins completely from linux Check if a file exists in jenkins pipeline Checkout Jenkins Pipeline Git SCM with credentials? Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject How to retrieve current workspace using Jenkins Pipeline Groovy script? Conditional step/stage in Jenkins pipeline Jenkins Pipeline Wipe Out Workspace Jenkins "Console Output" log location in filesystem how to setup ssh keys for jenkins to publish via ssh How to list all `env` properties within jenkins pipeline job? How to pass boolean parameter value in pipeline to downstream jobs? Get absolute path to workspace directory in Jenkins Pipeline plugin Running stages in parallel with Jenkins workflow / pipeline Is it possible to capture the stdout from the sh DSL command in the pipeline How can I test a change made to Jenkinsfile locally? How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin? How to change workspace and build record Root Directory on Jenkins? Jenkins vs Travis-CI. Which one would you use for a Open Source project? Jenkins - how to build a specific branch Run a command shell in jenkins How to change the JDK for a Jenkins job? Jenkins: Is there any way to cleanup Jenkins workspace? How to access parameters in a Parameterized Build? Is it ok to run docker from inside docker? Where can I find jenkins restful api reference? How to get build time stamp from Jenkins build variables? How do I clone a job in Jenkins? How to change port for jenkins window service when 8080 is being used Reading file from Workspace in Jenkins with Groovy script How/When does Execute Shell mark a build as failure in Jenkins?

Questions with branch tag:

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? Svn switch from trunk to branch What to do with branch after merge Creating a new empty branch for a new project How do I see the commit differences between branches in git? How can I combine two commits into one commit? Update a local branch with the changes from a tracked remote branch Get all files that have been modified in git branch Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo How to fetch all Git branches Difference between git checkout --track origin/branch and git checkout -b branch origin/branch Git fetch remote branch Renaming a branch in GitHub Gerrit error when Change-Id in commit messages are missing Switch to another branch without changing the workspace files View a file in a different Git branch without changing branches How to merge remote master to local branch How do I create a new Git branch from an old commit? How to get the current branch name in Git? Rebasing remote branches in Git How can I delete all Git branches which have been merged? Git merge errors How can I get a list of Git branches, ordered by most recent commit? How to discard all changes made to a branch? Renaming branches remotely in Git Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes? What is a tracking branch? How do I run git log to see changes only for a specific branch? git remote prune – didn't show as many pruned branches as I expected Git undo local branch delete Can I recover a branch after its deletion in Git? Forking vs. Branching in GitHub How do I list all remote branches in Git 1.7+? What are the differences between git branch, fork, fetch, merge, rebase and clone? How to find the nearest parent of a Git branch? How do I create a new branch? How do you stop tracking a remote branch in Git? How to commit my current changes to a different branch in Git Branch from a previous commit using Git Git: copy all files in a directory from another branch Mercurial — revert back to old version and continue from there

Questions with jenkins-pipeline tag:

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 Jenkins: Cannot define variable in pipeline stage get current date and time in groovy? Check if a file exists in jenkins pipeline Checkout Jenkins Pipeline Git SCM with credentials? Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject How to retrieve current workspace using Jenkins Pipeline Groovy script? Conditional step/stage in Jenkins pipeline Jenkins Pipeline Wipe Out Workspace How to list all `env` properties within jenkins pipeline job? How to pass boolean parameter value in pipeline to downstream jobs? Get absolute path to workspace directory in Jenkins Pipeline plugin Running stages in parallel with Jenkins workflow / pipeline How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)? Is it possible to capture the stdout from the sh DSL command in the pipeline How can I test a change made to Jenkinsfile locally? How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin? How to access parameters in a Parameterized Build? How can I execute Shell script in Jenkinsfile?