Blog about a mac person trying linux and windows

Recover a Lost or Missing Commit in Git

If you have ever lost a commit in Git, don’t worry there might be still a chance to recover it. For example I encountered a problem with Git, when I was pushing my commit to the remote server. For some reason my Git client had some error when sending the commit to the remote server. So the commit didn’t go through and the Git client deleted all my local modifications from my local machine. So I couldn’t try to send the commit again (as Git said there’s no modifications / commit to send). Basically it reset all my files to the state that they were when I last time made a successful commit to the server. Fortunately I found a way to dig up the lost commit and modifications that I have made with git reflog. Go inside your project folder, and then run the following:

git reflog

Now you should see a log of what has happened in your local repository. Every action that you have taken in your local repository (in your your local computer) should have an ID and what kind of action is it. So for example I found my lost commit few rows below in the log. The lost commit is in a form of “db123456 HEAD commit: your commit message”. Write down the ID string (in my example it’s the 8 characters long string “db123456”). Before we try to recover the lost commit, you should backup your project folder just in case, if something goes wrong or you need to try recovering again.

 

We will next reset the local git repository. Remember it will delete any modifications that you have made after the lost commit. So if you have multiple missing commits, then you should maybe try to recover them one by one. That’s why I recommend backup your project folder before recovering. To get back your missing commit, run the following command (remember to replace the ID with your ID that you have written down):

git reset --hard db123456

Now hopefully you should have recovered your lost commit.

Sources: