So, you just executed git reset --hard HEAD^ and discarded your last commit. But now you realize you really needed those changes. Don’t panic—Git likely still has your commit. When you reset, the discarded commit enters a “dangling” state, remaining in Git’s datastore until garbage collection runs. As long as you haven’t run git gc since the reset, you should be able to recover your lost commit.

Scenario Overview

Let’s go through an example to illustrate this process. Suppose you have just performed the following commands:

$ git show-ref -h HEAD
7c61179cbe51c050c5520b4399f7b14eec943754 HEAD

$ git reset --hard HEAD^
HEAD is now at 39ba87b Fixing about and submit pages so they don't look stupid

$ git show-ref -h HEAD
39ba87bf28b5bb223feffafb59638f6f46908cac HEAD

Here, your HEAD has moved back by one commit. If you realize you need the discarded commit, simply pulling from a remote repository won’t help because we assume that only your local repository knows about the commit.

Finding the Lost Commit

You need the SHA1 hash of the lost commit to recover it. You can confirm that Git still has the commit using the fsck command:

$ git fsck --lost-found
[... some blobs omitted ...]
dangling commit 7c61179cbe51c050c5520b4399f7b14eec943754

Another way to see if Git still knows about the commit is by using the reflog command:

$ git reflog
39ba87b... HEAD@{0}: HEAD~1: updating HEAD
7c61179... HEAD@{1}: pull origin master: Fast forward
[... lots of other refs ...]

In this example, the SHA1 hash of the lost commit is 7c61179.

Recovering the Lost Commit

To apply the lost commit back onto your current branch, you can use the git merge command:

$ git merge 7c61179
Updating 39ba87b..7c61179
Fast forward
  css/screen.css |    4 ++++
  submit.html    |    4 ++--
  2 files changed, 6 insertions(+), 2 deletions(-)

This command restores your lost changes and ensures that HEAD points to the recovered commit. From here, you can continue working as normal.

Alternative Methods

You could also check out the SHA1 hash into a new branch if you prefer, but merging is generally the quickest and easiest way to restore a lost commit once you have the hash.

Restoring a lost commit in Git is straightforward if you know the commit’s SHA1 hash. Using git merge allows you to quickly recover and continue your work. If you have other methods or additional tips, feel free to share them in the comments.

For more options and detailed guidance on recovering lost commits, Mathieu Martin’s illustrated guide to recovering lost commits with Git offers plenty of useful information.