CPCODELAB
Git & GitHub

Reflog: Recovering Lost Commits

9 min read

The Reflog Is Your Safety Net

Every time Git moves HEAD — a commit, reset, rebase, merge, or branch switch — it appends an entry to the reflog. The reflog is purely local and expires after 90 days by default, but within that window it can resurrect commits that appear to be gone forever.

bash
git reflog              # show HEAD movement history
git reflog show main    # show reflog for a specific branch

Output looks like this, newest first:

text
abc1234 HEAD@{0}: commit: add payment form
def5678 HEAD@{1}: reset: moving to HEAD~2
ghi9012 HEAD@{2}: commit: fix validation bug

Recovering a Reset-Away Commit

Ran git reset --hard HEAD~3 by accident and lost three commits? Find them in the reflog and restore:

bash
git reflog                        # locate the SHA before the reset
git reset --hard abc1234          # jump back to that SHA
# or, to restore just one lost commit onto your current branch:
git cherry-pick abc1234

Recovering a Deleted Branch

bash
git reflog                        # find the last commit SHA on the deleted branch
git switch -c recovered-branch abc1234  # recreate the branch at that SHA

Before any destructive operation (git reset --hard, git rebase, force-push), note the current SHA with git log --oneline -1. If anything goes wrong, that SHA is your escape hatch via the reflog.

Ready to test yourself?
Practice Git & GitHub— quiz & coding exercises