Detached head state exists in the git by design and cannot normally be turned off. You can get into detached head state only if you, after cloning your repository, do something like this
git checkout $specific_commit
for example if you are at the tip of the named branch master
#1 -> #2 -> #3
^
master
^
HEAD
and you do
git checkout HEAD~
which is commit right before what HEAD currently points to. Then you will end up in the following state
#1 -> #2 -> #3
^ ^
| master
|
HEAD
From this point you are in detached head state, i.e. HEAD points at a specific commit and not at the branch label. Prior to this HEAD was pointing at the branch label master
, which in turn was pointing at the specific commit (tip of branch). Now what ever commits you will make they will be on the separate branch that does not have a branch label (i.e. reference). Running git branch
will tell you if you in detached head state.
$ git branch
* (detached from 60e425a)
master
Notice the star *
, which indicates your current branch.
If you make new commit right now git repo will look like this.
#1 -> #2 -> #3
| ^
| master
|
\----> #5
^
HEAD
if you switch now back to master by doing git checkout master
then HEAD
will switch master
and branch that was created when you created commit #5
will no longer have any label, i.e. a symbolic reference to navigate to commit #5
. Which means that your commit is effectively lost.
Hence you have two options.
- If you do not want to end up in the detached head state then just do not do
git checkout $specific_commit
. Always stay at the tip of same named branch such as master
. You can verify that by running git branch
.
If you do find yourself in the detached head state and perhaps you already made commits that you do not want to "loose" then, as Flows suggested above, you need to create new branch label/reference like so
git checkout -b myNewBranch
which will make your repository look like so
#1 -> #2 -> #3
| ^
| master
|
\----> #5
^
myNewBranch
^
HEAD
Then if you witch back to master
you can always navigate back to commit #5
and all subsequent commits on that branch by doing git checkout myNewBranch
.
git reflog
is your friend.git checkout sha1
. here sha1 could be HEAD, FETCH_HEAD. And there are some other cases leading to detached HEAD state. If you know exactly which branch you are working with, it's okay to stay at detached HEAD state.