Skip to content

Git: Undo reset --hard

Sometimes one is distracted... and an accidental git reset --hard happens.
But within a few days after the accident, you can recover from the GIT reflog.

Facepalm moment

$ git reset --hard HEAD^
HEAD is now at 1a75c1d... added file1

Now all the local data of HEAD is gone...
And if you did not push that work to a remote repository, this is one of those facepalms moments.

Double facepalm

But there is a solution !

The git reflog...
You can read everything there is to know about the reflog in the official documentation...
But tl;dr:

The reference log, aka reflog, is a local chronological history of all the changes that are made to the references, which are names that point to the different objects used by Git (commit hashes, tags, branches etc)

We can use the reflog to view all those changes:

$ git reflog
1a75c1d... HEAD@{0}: reset --hard HEAD^: updating HEAD
f6e5064... HEAD@{1}: commit: added file2

To revert to the point before the hard reset accident:

$ git reset --hard f6e5064
HEAD is now at f6e5064... added file2

As one can see, it was possible to revert to commit f6e5064 and recover the otherwise lost work.

Note

  • By default, the reflogs are stored for 90 days...
  • The reflogs are local only. They are not sent to the repository when pushing commits

Comments