[!IMPORTANT] Git is very hard to lose data in. If you committed it, you can probably get it back.
You just ran git reset --hard and realized you wiped out 3 days of work. Panic sets in. You check git log, and your commits are gone.
Enter the Reflog.
The Hardware Reality: What is the Reflog?
The Reflog (Reference Log) isn’t magic. It’s a text file.
Look inside .git/logs/HEAD. It looks like this:
3a1b2c 9x8y7z You <you@example.com> 1700000000 +0000 commit: add login feature
9x8y7z 4d5e6f You <you@example.com> 1700001000 +0000 reset: moving to HEAD~1
It records:
- Old Hash
- New Hash
- User
- Timestamp
- Action/Message
Every time HEAD moves (commit, checkout, reset, merge), Git appends a line to this file. This allows you to “time travel” to any previous state of HEAD.
Reflog Explorer
Visualize how Reflog tracks your movements. Below is a simulation of a repository where a commit has been “lost” due to a reset.
Git Reflog
Project Init
Select an entry from the left to recover it.
How to Use Reflog
1. The Scenario
You are working on a feature. You accidentally run:
git reset --hard HEAD~2
Poof. Your last two commits are gone from the history. git log shows nothing.
2. View the Reflog
Run the reflog command:
git reflog
Output:
4a2b1c HEAD@{0}: reset: moving to HEAD~2
9x8y7z HEAD@{1}: commit: add login feature
1d2e3f HEAD@{2}: commit: setup database
4a2b1c HEAD@{3}: commit: project init
Notice HEAD@{1} and HEAD@{2}? Those are your “lost” commits! They are still there, just not pointed to by your branch.
3. Recover the Commit
To get your state back, you can simply reset hard to the entry before you messed up.
# Reset to where HEAD was before the destructive reset
git reset --hard HEAD@{1}
Or, if you want to inspect it first without modifying your current branch:
git checkout 9x8y7z
This puts you in a Detached HEAD state. If you verify your files are there, you can create a branch to save it:
git switch -c recovered-branch
Recovering a Deleted Branch
If you delete a branch that wasn’t merged, Git warns you. But if you force delete it (git branch -D feature-x), it’s gone.
Reflog can save you here too.
- Run
git reflog. - Look for the last entry where you were on that branch. It usually looks like:
checkout: moving from feature-x to main. - The hash associated with that move is the tip of your deleted branch.
- Recreate the branch:
git branch feature-x <hash>
Limitations
[!CAUTION] Reflog is LOCAL ONLY. It is not pushed to the server. If you delete your
.gitfolder, the reflog is gone.
Also, Git eventually cleans up old objects (garbage collection). By default, reflog entries expire after 90 days. So don’t wait three months to recover that lost code!