0
0
Gitdevops~5 mins

Reflog for finding lost commits in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you lose track of commits after changes like resets or branch switches. Git reflog helps you find those lost commits by showing a history of where your branches and HEAD have pointed.
When you accidentally reset your branch and want to recover previous commits.
When you switched branches and lost track of recent commits.
When you deleted a branch but want to find commits that were on it.
When you want to see a timeline of all recent changes to HEAD.
When you want to undo a recent commit or reset by finding its reference.
Commands
This command shows a list of recent positions of HEAD, including commits, resets, and checkouts. It helps you find lost commits by showing their references.
Terminal
git reflog
Expected OutputExpected
a1b2c3d (HEAD -> main) HEAD@{0}: commit: Fix typo in README f4e5d6c HEAD@{1}: reset: moving to f4e5d6c 123abcd HEAD@{2}: commit: Add user login feature 789ef01 HEAD@{3}: checkout: moving from feature to main
This command switches your working directory to the commit found in reflog, allowing you to inspect or recover lost work.
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 creates a new branch at the current commit so you can keep the recovered commit safe and continue working from it.
Terminal
git branch recovered-branch
Expected OutputExpected
No output (command runs silently)
Switch to the new branch to continue work from the recovered commit.
Terminal
git checkout recovered-branch
Expected OutputExpected
Switched to branch 'recovered-branch'
Key Concept

If you lose commits, git reflog shows where HEAD and branches pointed recently so you can find and recover them.

Common Mistakes
Trying to find lost commits using only 'git log' without reflog.
'git log' shows commits reachable from current branches, but lost commits after resets or checkouts may not appear.
Use 'git reflog' to see all recent HEAD positions including lost commits.
Not creating a branch after checking out a lost commit.
If you stay in detached HEAD state and make changes, you risk losing them if you switch branches.
Create a new branch at the recovered commit to save your work.
Summary
Use 'git reflog' to see recent HEAD movements and find lost commits.
Checkout the commit hash from reflog to inspect lost commits.
Create a new branch at the recovered commit to save and continue work.