1

So in my project I switched to a specific commit by:

git log (to check commit id)

git checkout commit_id

Then I added some changes there and commited them.

Then I checkout to another branch to do something there.

But now I can't return to my changes I made in the commit. When I just checkout to commit_id again, it's there without my changes. I don't have my new commit in my branch and also any new branch wasn't created. But I commited the changes I did there. So where did my changes go? Anyone knows? :(

  • 1
    Look in the reflog – marblewraith Mar 04 '20 at 09:53
  • That is because the commit you made added another commit on top of the one you checked out. This new one has a new hash, you need to check out this one instead. Hashes/commit id's doesn't refer to "a line of development", they refer to a specific state of the repository. It only stands to reason that if you keep checking out the same commit by id, you will get the exact same state every time. – Lasse V. Karlsen Mar 04 '20 at 09:57

2 Answers2

2

You've commited to a detached head.

That's usually a bad idea, specifically because of what you saw: the commit will be created, but no reference points to it, so it will just "drop away".

You can get back to it, by inspecting the reflog and finding the commit id of your newly created commit. But unless you create a branch or a tag there, or you cherry-pick that to another branch, that commit is "dangling" and will eventually be garbage collected.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
2

When you checkout to something that's not a branch, you get into the "detached HEAD" state: you aren't attached to any branch. When you commit from that state, everything works as usual, except that the new commit is not on any branch. If you then go checkout something else, that new commit is left dangling and disappears from logs, before getting GC'd sometime in the future.

To recover your lost commit, you can use git reflog which will give you the history of your head's position, and the SHA-1 of the dangling commit. You can then use git checkout -b new-branch <sha-1> to checkout to that commit and attach to a new branch.

Quentin
  • 62,093
  • 7
  • 131
  • 191