Merge detached HEAD back to origin/master – Git

I’ve recently had to use this awesome Git feature to fix a problem. I was aware that the last couple of check-ins were bad and I wanted to pick up and continue working from a known working point. Git allows you to do this by temporarily switching to a different commit. The command to do this is:

$git checkout c2744f95d

c2744f95d is the commit hash (SHA) so make sure you find and use the right commit hash. From that point on, you can continue working as normal. Another option is to create a totally new branch (a feature branch if you like):

$git -b new-branch-name c2744f95d

The new branch gives you a bit more flexibility. However, if you decide to go with the first option, then you will be working with a detached HEAD. In Git, the HEAD always points to the tip of the current branch. But since you’re not on a branch any more you’ve detached the HEAD. Once you’re happy with the changes, you then have the option to bring those changes to the main working branch using the following commands:

And with that, we fixed the problematic code while, at the same time, we avoided carrying over the bad commits. Git is amazing and I enjoy working with it more than any other source control solution ever. I hope you find these commands as useful as I did.


  • Share this post on