Git & GitHub · 10 min · 120 XP

Recover lost commits with reflog

Find commits that seem lost with the reflog, and know what it can't bring back.

Most I've lost my work moments aren't losses. Git keeps a private diary called the reflog: every time HEAD moves (a commit, a switch, a reset, a merge, a rebase), it writes down where it went. A commit that no branch points to any more still exists, and the reflog still has its ID.

text
$ git reflog
f89a07d HEAD@{0}: reset: moving to HEAD~1
711c658 HEAD@{1}: commit: Add coupon validation
f89a07d HEAD@{2}: commit: Fix rounding
bc674f3 HEAD@{3}: commit (initial): Add cart page

Read it from the top: HEAD@{0} is now, HEAD@{1} is one move ago, and so on. To get back to a moment, point your branch at it with git reset --hard 711c658. If you want to look before you leap, put a new branch there first (git branch rescue 711c658) and inspect it.

The reflog has limits. It's on your machine only, so a fresh clone doesn't have yours. Commits no branch points to are kept for about 30 days by default. And it only knows about commits: edits you never committed, then wiped with restore or reset --hard, were never in it.

Scenario: the wrong flag
$ git reset --hard HEAD~1
HEAD is now at f89a07d Fix rounding
$ git reflog -3
f89a07d HEAD@{0}: reset: moving to HEAD~1
711c658 HEAD@{1}: commit: Add coupon validation
f89a07d HEAD@{2}: commit: Fix rounding
Scenario: tidying up branches
$ git branch -D feature/coupons
Deleted branch feature/coupons (was c88774e).

Try it on your machine: make a commit on a practice branch, then remove it with git reset --hard HEAD~1. Find it in git reflog and bring it back with git reset --hard <id>. Then delete a branch with git branch -D and restore it from the ID git prints.

Loading your workspace…