Any checkout that is not the name of one of your branches will get you a detached HEAD.

The above scenario could be reproduced as below

  1. lists the remote branches
    git branch -r
        origin/Feature/f1234
        origin/master
    
  2. I want to checkout one locally, so I cut paste:
    git checkout origin/Feature/f1234
    
  3. Detached HEAD state
    You are in 'detached HEAD' state. [...])
    

Solution #1:
Do not include origin/ at the front of my branch spec when checking it out:

git checkout Feature/f1234

Solution #2:
Add -b parameter which creates a local branch from the remote

git checkout -b origin/Feature/f1234
git checkout -b Feature/f1234  #it will fall back to origin automatically

But, you have started making changes in the detached branch and you encounter that later. In such case commits will work but changes
won’t be reflected in branch in remote since it is detached. To address such an issue

  1. commit changes in detached local branch
  2. create a new branch
  3. checkout the branch you are already working so the connection with remote would be again established
  4. Now the new branch created in local contains your changes and checkout will fetch the original remote branch without changes
  5. Do git merge between two and push the code to remote now
git commit -m "....."
git branch my-temporary-work
git checkout master
git merge my-temporary-work
Posted in git.

Comments are closed.