Recovering a lost commit
- Git course
- Intermediate
- Lesson 46/82
- 4 min
Learn to recover a deleted commit with reflog.
How can a lost commit be recovered?
After git reset --hard, a commit may appear to have disappeared from the normal branch history. However, if the commit is still available in reflog, you can reach it again using its commit identifier. First find the entry with git reflog, then inspect the commit.
git reflog
git show a1b2c3da1b2c3d is an example commit identifier; use the identifier from your own reflog output.
Make a commit accessible again
You can create a new branch at the commit you found to make it accessible again. The command git branch recover a1b2c3d creates a recover branch pointing to the specified commit without changing your current position. This protects the commit with a branch reference.
git branch recover a1b2c3d
git switch recoverProtecting the commit with a branch first reduces the risk of accidentally losing your current work during recovery.
Practice Recover a lost commit
The example uses a1b2c3d as the lost commit identifier. First point a new branch named kurtar to this commit, then switch to that branch. Write both commands in the correct order.
Starter code
# Kayıp commit'i koru
# Kurtarma dalına geçSample solution
# Kayıp commit'i koru
git branch kurtar a1b2c3d
# Kurtarma dalına geç
git switch kurtarExpected output
Switched to branch 'kurtar'
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How can a commit lost after reset be found?
- By deleting the .gitignore file
- By running git config --global
- By inspecting the git reflog output Correct answer
- By running git remote remove
Explanation: Reflog can show HEAD positions from before the reset. This allows you to find the identifier of a commit that appears to be lost.
2 Attach the commit to a recovery branch
git branch kurtar ____
git branch kurtar a1b2c3d
Explanation: You use the lost commit's identifier when creating the branch. This makes the commit reachable through a branch reference.
3 Parts of the recovery process
| Term | Meaning |
|---|---|
git reset --hard |
Resets the working tree |
git reflog |
Finds previous positions |
git show |
Inspects commit contents |
git branch kurtar |
Points a branch to a commit |