In this lesson, you will learn how to use the Git reflog to recover commits that seem to have vanished after a risky reset or rebase.
The Safety Net You Didn't Know You Had
When you perform a "hard reset" or a rebase, Git might remove commits from your branch history. While git log will no longer show them, your work isn't actually deleted immediately. Git keeps a hidden, local record of every movement of your branch pointers called the Reference Log, or reflog.
Think of the reflog as an "undo" history for your entire repository. It tracks every time HEAD (the pointer to your current location) has changed, regardless of whether those changes were part of a branch history or an abandoned commit.
How to Recover a Lost Commit
If you accidentally reset your branch and lost your progress, follow these steps:
- View the Log: Run
git reflogin your terminal. You will see a list of entries looking something like this:a1b2c3d HEAD@{0}: reset: moving to HEAD~1 e4f5g6h HEAD@{1}: commit: Adding the final feature i7j8k9l HEAD@{2}: commit: Initial work - Identify the Target: Look for the entry just before your mistake. In the example above,
e4f5g6his the commit where you finished your work before the reset. - Restore the Work: You can now move your branch pointer back to that commit safely by using the
resetcommand with that specific hash:git reset --hard e4f5g6h
By pointing your branch back to that "lost" commit hash, you effectively bring it back into your active history. It is like traveling back in time to before the mistake occurred.
Note that the reflog is strictly local to your machine; it doesn't get pushed to GitHub, so it serves as your personal safety net for any operation performed on your local computer.
Key Takeaway: The reflog records every movement of your branch pointers, allowing you to recover "lost" commits by identifying their unique hash and resetting your branch back to that point in time.