Skip to content

Drill: Recover Lost Commits with Reflog

Goal

Use git reflog to find and recover commits that were lost after a reset, rebase, or other destructive operation.

Setup

  • A git repository with some commit history
  • Simulate a lost commit scenario for practice

Commands

Set up a practice scenario:

mkdir /tmp/reflog-drill && cd /tmp/reflog-drill && git init
echo "initial" > file.txt && git add file.txt && git commit -m "initial commit"
echo "important work" > file.txt && git add file.txt && git commit -m "important work"
echo "more work" > file.txt && git add file.txt && git commit -m "more work"

Simulate losing commits with a hard reset:

git reset --hard HEAD~2

View the reflog to find lost commits:

git reflog

Show the reflog with timestamps:

git reflog --date=relative

Inspect a reflog entry before recovering:

git show HEAD@{1}
git log --oneline HEAD@{1}

Recover the lost commit by creating a branch:

git branch recovered HEAD@{1}

Or recover by resetting back:

git reset --hard HEAD@{1}

Cherry-pick a specific lost commit:

git cherry-pick <commit-hash>

Search reflog for a specific message:

git reflog | grep "important work"

What to Look For

  • Reflog entries show every HEAD movement with the operation that caused it
  • HEAD@{N} references count backwards from the most recent HEAD position
  • Lost commits remain in the object store until garbage collection (typically 30+ days)
  • Each entry shows the commit hash, which can be used directly

Common Mistakes

  • Panicking and running more git commands that further modify the reflog
  • Running git gc or git prune which permanently removes unreachable objects
  • Confusing HEAD@{1} (reflog position) with HEAD~1 (parent commit)
  • Not creating a branch from the recovered commit before doing more work

Cleanup

rm -rf /tmp/reflog-drill