Git: How to return from 'detached HEAD' state

Viewed 158359

If one would checkout a branch:

git checkout 760ac7e

from e.g. b9ac70b, how can one go back to the last known head b9ac70b without knowing its SHA1?

6 Answers

You may have made some new commits in the detached HEAD state. I believe if you do as other answers advise:

git checkout master
# or
git checkout -

then you may lose your commits!! Instead, you may want to do this:

# you are currently in detached HEAD state
git checkout -b commits-from-detached-head

and then merge commits-from-detached-head into whatever branch you want, so you don't lose the commits.

In general: git checkout <branch*> (git checkout master is a special case).

*from which we (accidentally) detached a commit (using git checkout <commit_hash>)

Just in case anyone has the same edge case as me: I have a branch called test and was trying to make a branch called test/my-experimental-feature. That confused git because it thought I was referring to a branch that already exists. I changed it to test--my-experimental-feature and it worked fine.

Related