I want to get git current checkout BRANCH NAME in my Jenkins file here is the code snippet... Here I am trying to push a file to my current branch I have tried many things could not find it...

stage('Push yaml file to bitbucket'){
    withCredentials([usernamePassword(credentialsId: '8e2ca0a6-2dc5-4f89-b76a-03076d6b0843', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
      sh '''
        echo '#!/bin/sh' > /home/jenkins/git_askpass.sh
        echo "exec echo \"${GIT_PASSWORD}\"" > /home/jenkins/git_askpass.sh
        chmod 775 /home/jenkins/git_askpass.sh
        echo "user: ${GIT_USERNAME}"
        export GIT_ASKPASS
        cat /home/jenkins/git_askpass.sh
        git status
        git checkout feature/OSCCX-44(here I want branch name )
        git config --global user.email "xyz.com"
        git config --global user.name "xyz"
        git add yaml_dev/04-idm-frontend-depl.yaml                
        git commit -m "jenkins commit"
        git push https://${GIT_USERNAME}@bitbucket/repository '''

If you check the Git plugin documentation, you can see that there is a GIT_BRANCH environment variable that you can use in your pipeline.

GIT_BRANCH - Name of the remote repository (defaults to origin),
             followed by name of the branch currently being used,
             e.g. "origin/master" or "origin/foo"

So, in your pipeline:

stage('Push to Bitbucket') {
    steps {
        withCredentials([usernamePassword(credentialsId: '8e2ca0a6-2dc5-4f89-b76a-03076d6b0843',
                                          passwordVariable: 'GIT_PASSWORD',
                                          usernameVariable: 'GIT_USERNAME')]) {
            sh '''
            # Content omitted
            git checkout ${GIT_BRANCH}
            # Content omitted
| improve this answer | |

Note that if you're not actually checking out a Jenkinsfile (if you're coding in the Pipeline Script config window), GIT_BRANCH will be null, and Hedi Nasr's answer will fail (you can access the var with ${env.GIT_BRANCH} instead to avoid the hard fail, but it will still be null).

You don't give any information about how you checked out the project, so I'm going to assume you cloned it at some point during the execution of your Jenkinsfile. In that case, the repository will be in a detached state, even if you cloned it with a target branch:

git status
# HEAD detached at 9a92344

In this case before you can commit you need to checkout your branch as Hedi Nasr points out. You should know your target branch in advance, and can inject it with envInject's Properties Content if you need to vary by instance.

You can also discover branches with:

git branch -a
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.