Recently, I came across a situation where I checked out a git branch and it showed me this message related to detached HEAD state:
You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout.
I guess this happened because the branch that I was checking out was rebased. Otherwise, it usually happens when you checkout a commit with its hash. But in my case, I was checking out a branch. Anyway, this is a special state called “detached HEAD”. While you can commit changes in this state, those commits don’t belong to any branch and will become inaccessible as soon as you check out another branch. But what if you do want to keep those commits?
The answer, unsurprisingly, is to use the “checkout” command again and you can use the same branch again:
git checkout <branch> #now you're in detached head state # do some work and stage it git add --all git commit -m "add some work while in detached head state" git branch <branch> git checkout <branch>
Pretty easy, right?