0
0
Gitdevops~5 mins

Recovering lost commits with reflog in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you lose track of commits in Git by accident, like after a reset or branch deletion. Git reflog helps you find those lost commits so you can get them back.
When you accidentally reset your branch and lose recent commits.
When you deleted a branch that had commits you want to recover.
When you want to find a commit that is no longer visible in your branch history.
When you want to undo a mistaken git reset or checkout.
When you want to recover work after a rebase or merge gone wrong.
Commands
This command shows a list of recent changes to HEAD, including commits that might be lost from the current branch view.
Terminal
git reflog
Expected OutputExpected
a1b2c3d (HEAD -> main) HEAD@{0}: commit: Fix typo in README f4e5d6c HEAD@{1}: commit: Add user login feature 9a8b7c6 HEAD@{2}: reset: moving to HEAD~2 3d2c1b0 HEAD@{3}: commit: Initial commit
This command checks out the lost commit by its hash from the reflog so you can inspect or recover it.
Terminal
git checkout a1b2c3d
Expected OutputExpected
Note: switching to 'a1b2c3d'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches. HEAD is now at a1b2c3d Fix typo in README
This command creates a new branch at the recovered commit so you can keep it safely and work on it.
Terminal
git branch recovered-commit
Expected OutputExpected
No output (command runs silently)
Switch back to your main branch after creating the recovery branch.
Terminal
git checkout main
Expected OutputExpected
Switched to branch 'main'
Key Concept

If you lose commits, git reflog lets you find their hashes and recover them even if they are no longer in your branch history.

Common Mistakes
Trying to recover commits without checking reflog first
You won't see lost commits in normal git log, so you might think they are gone forever.
Always run git reflog to find lost commit hashes before giving up.
Not creating a branch after checking out a lost commit
If you stay in detached HEAD state and switch branches, you can lose the recovered commit again.
Create a new branch at the recovered commit to keep it safe.
Summary
Use git reflog to see recent HEAD changes including lost commits.
Checkout the lost commit by its hash from reflog to inspect it.
Create a new branch at the recovered commit to save it.
Switch back to your main branch to continue normal work.