How to Undo Git Reset

Everyone makes a mistake and one of the most useful features of any version control system is the system of undoing changes. Here, you will get a simple and straightforward way of undoing the git reset.

Watch a course Git & GitHub - The Practical Guide

Suppose that you have run git reset HEAD~1 by mistake, which has deleted the latest commit from your local branch and, now, you want to restore that commit. Below, we will demonstrate how to do it.

Undoing git reset with git log

Viewing reference updates

Git keeps a log of all reference updates (e.g., checkout, reset, commit, merge). Run the git reflog command to view them:

git reflog

The output may be something like this:

49ab751 HEAD@{0}: reset: moving to HEAD~1
b53c078 HEAD@{1}: Change the length ...

Undoing git reset

Run the following command to undo your mistake and go back at the commit before resetting:

git reset HEAD@{1}

Undoing git reset with the --hard option

If the remote-tracking branch corresponding to your branch is synchronized with your current branch before resetting, you can call the command below to undo the git reset: (suppose, the name of remote is origin, which is by default):

git reset --hard origin/<branch-name>

The git reset Command

The git reset command is used for undoing changes. It is somewhat similar to git checkout as they both operate on HEAD. The git checkout command works exclusively on the HEAD reference pointer, while git reset passes the HEAD reference pointer and the current branch reference pointer.

Take into account that you should not use git reset <commit> when there are snapshots after the <commit>, which are moved to a public repository. When you publish a commit, remember that other team members also rely on it. Removing commits that are being developed by other members of the team will cause lots of issues. It is best to remove local changes.

The Three Trees

Git uses three different versions of files for the workflow of adding and retrieving commits. These systems include:

  • HEAD (the commit history)
  • the staging area
  • the working directory

HEAD points to your branches, like the master branch by default. HEAD is a reference that changes and points to the currently checked out branch, and through that branch, the last commit on it.

The staging area or index is where commits are prepared. The staging area compares the files in the working tree to the files in the repository. When making changes in the working tree, the staging area marks the file as changed before it is committed.

The working tree or working directory is a version of a particular snapshot or a particular commit of a checked-out project. The working directory represents the files on your computer's file system available to the code editor to apply changes. It is the version of the Git history that HEAD is pointing at, at any specified moment.

Each of these trees does a different job, but they are equally crucial for Git operation.