What happens to git commits created in a detached HEAD state?

This is what happened:

I have a branch A. On branch A I committed a bunch of changes. I was not happy with the code, so I checked out the previous commit in branch A. I then made a bunch more changes and committed them on branch A. Now I can not find this commit anywhere. Did I lose this code?


Solution 1:

The old commit is still in the reflog.

git reflog

This will show a list of commits, and the "lost" commit should be in there. You can make it into a new branch. For example, if the SHA-1 is ba5a739, then you can make a new branch named "new-branch" at the old commit with:

git branch new-branch ba5a739

Note that "lost" commits will get deleted when the database is pruned.

Solution 2:

Your commits are still available in the reflog, as pointed out already. In addition to the other answers, here is a way to take over the detached HEAD commits into your current branch directly, without creating and merging a new branch:

  1. Look up the SHA-1 hashes of the commits you made in detached HEAD state with

    git reflog
    
  2. Then execute, with all the commit hashes ordered from oldest to most recent:

    git cherry-pick <hash1> <hash2> <hash3> ...
    

    For example if I had only one, given in the "first 7 characters" short hash format:

    git cherry-pick a21d053
    

This will create new commits to your current branch, one commit per detached-HEAD-commit hash that you mention in the command. It also takes over the original commit messages.