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:
View the reflog to find lost commits:
Show the reflog with timestamps:
Inspect a reflog entry before recovering:
Recover the lost commit by creating a branch:
Or recover by resetting back:
Cherry-pick a specific lost commit:
Search reflog for a specific message:
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 gcorgit prunewhich permanently removes unreachable objects - Confusing
HEAD@{1}(reflog position) withHEAD~1(parent commit) - Not creating a branch from the recovered commit before doing more work