Skip to main content
  1. Learn
  2. Software Development
  3. Guides
  4. Git tutorial
  5. How to use Git
  6. How to manage history in Git
  7. Reset a previous commit
GuidesSoftware DevelopmentBacklog
Git

Project and code management together.

Reset a previous commit

Resetting a commit in Git allows you to fine-tune and adjust your commit history, providing the flexibility to remove or modify commits as needed. Whether you need to undo a commit, modify a previous commit, or discard unwanted changes, Git offers the git reset command to help you reset your commit history and maintain a clean and organized development timeline.

In this part of our tutorial, we will explore the process of resetting a commit in Git.

Go to the git-tutorial/tutorial3 directory you previously downloaded.

When you examine the history of this repository, it will look like the following:

Current history

We are going to undo the previous two commits using the git reset command.

First, open the sample.txt file and verify that its content looks like the following:

Anyone can learn Git with this tutorial and Backlog
add: Register a change in an index
commit: Save the status of an index
pull: Obtain the content of the remote repository

Use the reset command to delete the previous two commits, as seen below.

Delete the commit
$ git reset --hard HEAD~~
  HEAD is now at 326fc9f append description of the add command

The sample.txt file will no longer contain the last two lines (i.e., “commit: Save the status of an index” and “pull: Obtain the content of the remote repository”).

Verify that these commits are no longer in the history with the git log command.

$ git log
  commit 326fc9f70d022afdd31b0072dbbae003783d77ed
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:17:56 2022 +0900

      append description of the add command

  commit 48eec1ddf73a7fb508ef664efd6b3d873631742f
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:16:14 2022 +0900

      first commit

ORIG_HEAD points to the original commit before reset takes place. This comes in handy when you accidentally issue a reset.

You can restore the previous history by executing a reset to ORIG_HEAD.

$ git reset --hard ORIG_HEAD
  HEAD is now at 0d4a808 append description of the pull command

Subscribe to our newsletter

Learn with Nulab to bring your best ideas to life