Home » Development » How to recover lost git commits

We’ve all been there, your working on a large group of code with some developers and you write a chunk of code for a new feature and commit it.  A few weeks later you go to use it and find somehow somewhere someone deleted your code.  It’s gone never to be seen again.  But hey, this is git, it promised to keep track of all of our code for us.  It’s got to be in there somewhere still right?  Yes and along comes git grep to the rescue.  If you can recall the name of some variables you may have used in your code you can use git grep to search the commit history to find it.

One thing you need to keep in mind if you have a repo with more then one branch you may need to switch branches to search the different commit histories

Pay dirt!

[analog@dev htdocs]# git grep 'display_pri' $(git rev-list --all)
6e6242576c9e4874b0edbb0cceb9adec1b380a47:.upgradeScripts/displayPrice.php:                                              $json['prices'][$i]['display_price'] = 1;
6e6242576c9e4874b0edbb0cceb9adec1b380a47:.upgradeScripts/displayPrice.php:                                              $json['prices'][$i]['display_price'] = 0;

So what are we doing here? I’m asking git to search all the commits listed with git rev-list –all for a string that contains display_pri Right away you see it finds a commit that has some code with that string. Now we can use git checkout 6e6242576c9e4874b0edbb0cceb9adec1b380a47 to switch to that commit like we would a branch. Do not commit anything in this branch/commit. You are now in a detached HEAD, this means that if you commit from here you could overwrite other code and be in the same boat all over again. Instead checkout the commit in a different place and copy the code to a new current branch to add it back

Leave a Reply

Your email address will not be published. Required fields are marked *

</Random> is Stephen Fry proof thanks to caching by WP Super Cache