Undoing and recovery

git reflog: how to recover lost commits

git reflog is your safety net for recovering lost commits, deleted branches, and bad resets. Learn how to read it and restore your work.

8 minute lesson

~~~

You can recover lost commits with git reflog, even after a bad reset --hard or a deleted branch. Git keeps a local log of where HEAD has been. That log is your safety net.

What the reflog records

The reflog stores every time HEAD moves in your local repo. A commit, a reset, a checkout, a rebase. Each entry gets a short hash and a message.

This log lives only on your machine. It is not pushed to the remote. Your teammates cannot see your reflog.

Run this to see the last moves:

git reflog

Example output:

a1b2c3d HEAD@{0}: reset: moving to HEAD~3
e4f5a6b HEAD@{1}: commit: add payment form
c7d8e9f HEAD@{2}: commit: fix checkout bug

HEAD@{0} is the most recent move. HEAD@{1} is one step back. The hash on the left is the commit you can recover.

Recover after a bad reset —hard

Say you ran git reset --hard HEAD~3 and lost three commits. The commits still exist. Git just moved HEAD away from them.

Find the commit before the reset in the reflog:

git reflog

Look for the line right before reset: moving to. That hash is your work.

Reset back to it:

git reset --hard e4f5a6b

Your commits are back. If you only want one commit, cherry-pick it instead:

git cherry-pick e4f5a6b

Recover a deleted branch

You deleted a branch with git branch -D feature/payments. The commits are still in the reflog if you worked on that branch recently.

Check the reflog for that branch:

git reflog show feature/payments

Or search the main reflog for the last commit on that branch. Then recreate the branch:

git branch feature/payments e4f5a6b

You are back where you left off.

Cherry-pick or reset to a reflog entry

You have two main options once you find the right hash.

git reset --hard <hash> moves your current branch to that commit. Use this when you want the whole branch back.

git cherry-pick <hash> copies one commit onto your current branch. Use this when you only need specific work.

You can also checkout a detached state to inspect first:

git checkout e4f5a6b

Look around. When you are happy, create a branch or reset your main branch to that point.

Reflog expiry

Reflog entries expire. The default is 90 days for reachable commits. Unreachable commits may expire after 30 days.

After expiry, Git may garbage-collect those commits. Recovery gets harder or impossible. Do not treat reflog as a backup strategy. Push your work to the remote regularly.

My advice: run git reflog the moment you think you lost something. The entry is almost always there if it happened today.

For more Git basics, see the Git guide. The Git cheat sheet is handy when you need a quick command reference.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →