The Problem Scenario
Say there are 3 commits in your repository.
commit 3(third)
commit 2(second)
commit 1(initial)
and you accidently reset to 2nd commit:
git reset --hard HEAD~1
Finding the Lost Commit
you use reflog:
git reflog
it will show:
abcdef1 HEAD@{0}: reset: moving to HEAD~1
1234567 HEAD@{1}: commit: Add third line
Here, the second line tells you, HEAD@{1} was pointing to the commit you accidently lost. It’s hash is like 1234567. To recover this, we take following method:
Recovery Options
Option 1: checkout to the commit and create branch.
git checkout 1234567
git checkout -b branch-with-recovered-third-commit
Option 2: move current branch to the lost commit:
git reset --hard 1234567
Summary of Steps
To summarize the steps:
- View reflog.
git reflog - Locate the hash of lost commit(the one before your mistake).
- Recover the lost commit.
git checkout <hash>orgit reset --hard <hash> - Preserve it.
git checkout -b recovered-branch