How to get branch name in jenkins shared library
The GIT_BRANCH environment variable should give you what you want. It won't work in pipeline until Jenkins 2.60 and upgraded pipeline model definition plugin.
If you are using a pipeline job, you can
- Capture object returned from scm checkout
- Reference environment variable
pipeline { // ... stages { stage('Setup') { steps { script { // capture scm variables def scmVars = checkout scm String branch = scmVars.GIT_BRANCH // or use the environment variable branch = env.GIT_BRANCH } } } // ... }}
I ended up using this:
env.CHANGE_BRANCH ?: env.GIT_BRANCH ?: scm.branches[0]?.name?.split('/')[1] ?: 'UNKNOWN'
However, this requires me to approve several things in In-Script Approvals
page.