Recover lost commits with the reflog

careful advanced #reflog#recover#lost#reset

When to use this: You reset, rebased or deleted a branch and now commits or work seem to be gone.

Be careful with this one. Check git status before you run it.

Before you start

Steps

  1. Look at where HEAD has been

    terminal
    git reflog

    Each line is a place HEAD pointed to, newest first, like HEAD@{3}. Find the line just before things went wrong.

    Expected output
    8c4d7e0 HEAD@{0}: reset: moving to HEAD~2
    a91b3c4 HEAD@{1}: commit: Add contact page
    3f2a1b9 HEAD@{2}: commit: Fix nav
  2. Rescue the commit onto a new branch

    terminal
    git switch -c rescue a91b3c4

    Safest option: puts a branch label on the lost commit so nothing can lose it again.

  3. Or move the current branch back to it

    terminal
    git reset --hard a91b3c4

    Moves the current branch to that commit. Discards uncommitted changes, so only run it on a clean tree.

How to verify it worked

  • git log --oneline shows the commits you thought were lost.

Common errors and fixes

The commit is not in git reflog It may have been in another clone, or expired. Check GitHub (a pushed commit remains on the server), or git fsck --lost-found for unreachable objects.

Q&A

How long does the reflog keep entries?

By default about 90 days for reachable entries and 30 days for unreachable ones. It is local to each clone and is not pushed.

Practice these as flashcards →

Terms in this scenario

Related scenarios

My notes

Saved in this browser only.