Jenkins pipeline branch name returns null

My workaround, Don't know if work for someone else..

def branchName = getCurrentBranch()
echo 'My branch is' + branchName

def getCurrentBranch () {
    return sh (
        script: 'git rev-parse --abbrev-ref HEAD',
        returnStdout: true
    ).trim()
}

This variable only works in a multibranch pipline:

BRANCH_NAME For a multibranch project, this will be set to the name of the branch being built, for example in case you wish to deploy to production from master but not from feature branches.

I was testing in a normal pipline


In Jenkins there is two pipeline options:

  1. New Item -> Pipeline --> env.BRANCH_NAME return branch null
  2. New Item -> Multibranch Pipeline --> env.BRANCH_NAME return branch master or branch name