Search code examples
gitbitbucketbranch

git checkout branch causes detached head


Trying to checkout a remote branch that does not yet exist on my system. For the purposes of this question, none of the 3 branches exist on my system.

git branch -r shows a list of relevant branches on the remote:

  origin/V2.0005B2
  origin/V2.0005B3
  origin/V2.0005B4

I can run git checkout V2.0005B2 or git checkout V2.0005B4 fine and it creates a local copy and sets it up to track.

But when I try to run git checkout V2.0005B3 it puts me in a detached head state every time. It happens on every machine I've tried it on.

SourceTree can check out this branch just fine as well as git fork. But the Git bash command line has this problem.

I am only hoping there is nothing wrong with this branch, otherwise it seems to work fine as long as it is originally checked out using one of those other utilities. The branch lives in BitBucket and I've logged in there to see if I could see anything unusual, but it looks the same as the others.

Thanks, Dave


Solution

  • Check your local tags :

    git tag --list
    

    If you have a tag named V2.0005B3, running git checkout V2.0005B3 will result in your situation : a detached HEAD state, on the commit pointed at by that tag.

    • If you want to create a branch there, run :
    git checkout -b V2.0005B3
    git branch -u origin/V2.0005B3
    
    # or shorter suggested by @torek :
    git checkout --track origin/V2.0005B3
    
    • If you want to delete the tag :
    # delete your local tag :
    git tag -d V2.0005B3
    
    # delete the remote tag :
    git push -d origin refs/tags/V2.0005B3
    

    If this is a shared repo, tell all of your colleagues to also delete their local tag ; this will avoid surprising behaviors on their machine, and mitigate the possible reappearance of that tag on the central repo.