Git & Command Line Tutorial · Git Superpowers · Lesson 19 of 20
Recovering Lost Work with reflog
Git rarely loses anything: use the reflog to find commits after a bad reset, a deleted branch or a messed-up rebase, and bring them back.
The safety net
The reflog records every position HEAD and your branches have pointed to in this repository, for about 90 days. Even after git reset --hard, a deleted branch or a rebase gone wrong, the commits still exist; the reflog tells you their hashes.
git reflog # HEAD@{0}, HEAD@{1}, ... with what happened
git switch -c rescued HEAD@{2} # a branch at an old position
git reset --hard HEAD@{1} # or move the current branch back
What the reflog can't recover: changes you never committed (that's why committing often, even to a WIP branch, is a good habit).
git init -b main --quiet project && cd project
echo "v1" > app.txt && git add . && git commit -m "Version 1" --quiet
echo "v2" > app.txt && git commit -am "Version 2 (important!)" --quiet
echo "v3" > app.txt && git commit -am "Version 3" --quiet
git reset --hard HEAD~2 --quiet # oops: two commits gone from main
echo "--- log after the mistake:"; git log --oneline
echo "--- reflog:"; git reflog --format="%gd %h %gs" | head -4
git reset --hard HEAD@{1} --quiet # back to where we were before the reset
echo "--- recovered:"; git log --oneline
git switch -c experiment --quiet && git commit --allow-empty -m "Experiment" --quiet
git switch main --quiet && git branch -D experiment > /dev/null
lost=$(git reflog --format="%h %gs" | grep "commit: Experiment" | cut -d' ' -f1)
git branch experiment "$lost"
echo "--- deleted branch restored at: $(git log --oneline -1 experiment)"
Output
--- log after the mistake:
df32bb9 Version 1
--- reflog:
HEAD@{0} df32bb9 reset: moving to HEAD~2
HEAD@{1} 4c44167 commit: Version 3
HEAD@{2} ed614d6 commit: Version 2 (important!)
HEAD@{3} df32bb9 commit (initial): Version 1
--- recovered:
4c44167 Version 3
ed614d6 Version 2 (important!)
df32bb9 Version 1
--- deleted branch restored at: dd68330 ExperimentRun this on your computer — see “Get Started” for setup.
Test yourself
You ran git reset --hard and lost two commits. What helps you get them back?
git loggit refloggit statusgit diff
Show answer
Answer: git reflog