Git Detached HEAD lost data

923 views Asked by At

Somehow, I ended up with a detached HEAD. I made some commits and they showed up in my commit history as HEAD (but master was several commits behind). Then I tried to fix the detached head by checking out master.

Now I don't see my previous commits to the detached HEAD. Are they gone forever?

3

There are 3 answers

4
Kevin On BEST ANSWER

No. Check the reflog (git reflog).

0
Andrew C On

Unless you are using a stone age version of Git the messages it prints out are pretty good (these are from 2.2.0, but I think they have been this way since 1.8.X or earlier)

When you first went into detached head state it should have told you exactly how to create a branch to work on.

Note: checking out 'HEAD~1'.

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.

If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example:

git checkout -b new_branch_name

And when you left detached head state you should have gotten this message

Warning: you are leaving 1 commit behind, not connected to any of your branches:

27c4eec foo

If you want to keep them by creating a new branch, this may be a good time to do so with:

git branch new_branch_name 27c4eec

If you didn't see these messages then you should consider upgrading your version of Git.

If you did see these messages then just follow the instructions they printed out.

0
jub0bs On

Are [my previous commmits ] gone forever?

No. Even though those commits don't show up in the output of git log, they still exist in the entrails of your repository, and you can still retrieve them; in such cases, the reflog is your safety net.

Without more information, it's difficult to provide a sequence of commands that would definitely get you out of trouble, but you can do the following:

  1. Open the reflog of your master branch by running

    git reflog master
    
  2. Using commit messages as cues, identify the the commit you want your master branch to point to; write down (on a piece of paper) the number of the corresponding entry in the master reflog. Exit the reflog.

  3. Make sure master is the current branch:

    git checkout master
    
  4. Run

    git reset master@{<n>}
    

    where <n> stands for the number of the reflog's entry corresponding to the commit of interest.

After that, master should point to the desired commit, like before you ended up with a detached HEAD.