The reflog and recovering lost work
Almost nothing you commit is really lost. Find it and bring it back.
The reflog is a local diary of where HEAD and each branch pointed over time. After a bad reset, rebase or deleted branch, the commits still exist for a while. The reflog tells you their hashes.
git reflog
# 3f2a9c1 HEAD@{0}: reset: moving to HEAD~3
# 9b1e4d2 HEAD@{1}: commit: add search page
# ...Recover from a bad reset
git reset --hard 9b1e4d2 # go back to where you were
# or keep the old state as a new branch first:
git branch rescue 9b1e4d2Recover a deleted branch
git reflog # find the last commit of that branch
git switch -c restored 7c3d5a0Uncommitted work
The reflog only knows about commits. Changes you never committed or staged, and a git reset --hard or git checkout . over them, are usually gone. Commit or stash often. Files you staged with git add may still be found with git fsck --lost-found.
CarefulReflog entries are local, expire (by default after about 90 days for reachable and 30 days for unreachable commits) and git gc can delete the objects. Recover quickly, and never rely on the reflog as a backup.
NoteBefore any risky operation (a big rebase, a history rewrite) create a safety branch: git branch backup-before-rebase.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.