Abecto
5Feb/110

Retrieving lost Git commits

From time to time I've managed to "lose" commits in Git, usually after I have initialised a submodule in a project and forgot to checkout a specific branch before committing changes. When I eventually do realise my mistake, I need to get those commits back into the relevant branch - in this case, master. Here's how it's done.

git reflog

This command will return something like:

902532b HEAD@{5}: commit: Doing some stuff on master now...wait where's my previous commits?
7f6c682 HEAD@{7}: checkout: moving from 3a311d8f746f903e15ce145a3e7683e0d53536fb to master
3a311d8 HEAD@{8}: commit: Added some more stuff
56f7716 HEAD@{9}: commit: Added some stuff
7f6c682 HEAD@{10}: checkout: moving from master to 7f6c6821c80baff91492af4909f1012876ef6249

56f7716 and 3a311d8 are the SHA identifiers of the commits that are floating around in the git void, attached to no branch, so I want to move them into the master branch. Starting with the first commit:

git checkout 56f7716

This will return output similar to:

Note: moving to '56f7716' which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
git checkout -b
HEAD is now at 56f7716... Added some stuff

Pretty self explanatory. Let's do what it suggests and create a branch at this point in the history tree. We can then merge that branch into master (or whichever branch it belongs to).

git checkout -b temp_branch
git checkout master
git merge temp_branch

The commit is now in master where it belongs. Rinse and repeat for commit 3a311d8 and all is well in the world again!

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.