Recovering Lost Commits in Git
Git is a very powerful tool, and with great power comes great responsibilities. If not used and handles properly, It might cause you to lose your commits. There might be situations when you may find all of your work missing at once.
If you have regularly committed your work, there is a way to recover these lost commits.
This tutorial will aim at using the
git reflog
and the
git cherry-pick
commands to recover your lost commits in Git.
Note: Using the reflog will only work for a certain amount of time after the commits are lost. Git cleans the reflog periodically, so don’t wait too long!
Procedure
The first step to recovering your lost commits is to recover the list of all your previous commits and actions done on the repository.
Note: Keep in mind that the given commit hashes and signatures may differ from that of your local repository. Replace all relevant information with the info corresponding to your log.
Run this command
git reflog
After running the command this is what you will see as the output.
$ git reflog c9f9669 HEAD@{0}: commit: Fixed test cases to run on Unix b3ca8a4 HEAD@{1}: pull: Fast-forward 54ba188 HEAD@{2}: pull origin master: Fast-forward e659a21 HEAD@{3}: reset: moving to HEAD~1 12944d8 HEAD@{4}: reset: moving to HEAD~1 6f40152 HEAD@{5}: reset: moving to HEAD~1 3de61ba HEAD@{6}: pull: Fast-forward e659a21 HEAD@{7}: reset: moving to HEAD^1 12944d8 HEAD@{8}: reset: moving to HEAD^1 6f40152 HEAD@{9}: reset: moving to HEAD^1 3de61ba HEAD@{10}: commit: Removed Query object 6f40152 HEAD@{11}: pull: Merge made by the 'recursive' strategy. 12944d8 HEAD@{12}: commit: API touchups --- We want to recover this commit. e659a21 HEAD@{13}: commit: Test enhancements 07419e1 HEAD@{14}: pull: Fast-forward
Find of the Hash of the commit you want to recover, For ex-12944d8.
Now use the following command to bring your lost commit back.
git cherry-pick 12944d8
Recovered Commit
That’s it! Your work should be recovered soon with the following success commands:
Finished one cherry-pick. [master 12944d8] API touchups 3 files changed, 36 insertions(+), 3 deletions(-)
In case of a Merge conflict
If there is a merge conflict, the following message will show up.
error: could not apply 12944d8... API touchups hint: after resolving the conflicts, mark the corrected paths hint: with 'git add ' or 'git rm ' hint: and commit the result with 'git commit'
using the git status command can help you identify what has to be done.
Please Login to comment...