GIT Reset Repository to Previous Commit


To revert a Git repository to a previous commit, you can use the git revert or git reset command depending on your use case. Here are the steps to perform each method:

Using git revert

The git revert command creates a new commit that reverses the changes made in the specified commit, effectively undoing it. This is useful if you want to keep a record of the original commit and the changes that were undone.First, identify the commit hash that you want to revert to using the git log command:

$ git log
commit 93f28a0a8d3f6d14f6a7c4d4a8eaaab328e4b09a
Author: John Doe <[email protected]>
Date:   Wed Mar 31 10:00:00 2022 -0400

    Added feature X

commit b55a05f1c12e3e0d9f3b05a54e0e7d0a79a2d7c1
Author: Jane Smith <[email protected]>
Date:   Tue Mar 30 14:00:00 2022 -0400

    Made changes to feature Y

commit 7e42ca786e2fa2f042dcf534ee8b621394f79837
Author: John Doe <[email protected]>
Date:   Mon Mar 29 09:00:00 2022 -0400

    Added feature Y

Let’s say you want to revert to commit b55a05f1c12e3e0d9f3b05a54e0e7d0a79a2d7c1. You can run the following command:

$ git revert b55a05f1c12e3e0d9f3b05a54e0e7d0a79a2d7c1

This will create a new commit that undoes the changes made in the specified commit

Using git reset:

The git reset command removes the specified commit and all subsequent commits, effectively resetting the repository to the state it was in before the commit was made. This is useful if you want to completely remove the changes made in the specified commit and all subsequent commits.

First, identify the commit hash that you want to reset to using the git log command:

$ git log
commit 93f28a0a8d3f6d14f6a7c4d4a8eaaab328e4b09a
Author: John Doe <[email protected]>
Date:   Wed Mar 31 10:00:00 2022 -0400

    Added feature X

commit b55a05f1c12e3e0d9f3b05a54e0e7d0a79a2d7c1
Author: Jane Smith <[email protected]>
Date:   Tue Mar 30 14:00:00 2022 -0400

    Made changes to feature Y

commit 7e42ca786e2fa2f042dcf534ee8b621394f79837
Author: John Doe <[email protected]>
Date:   Mon Mar 29 09:00:00 2022 -0400

    Added feature Y

Use the git reset command with the --hard option to reset the repository to the previous commit. For example, if the commit hash is abc123, you would run:This command will remove all commits after the specified commit and reset the state of your working directory to match the specified commit.

git reset --hard abc123

If you’ve already pushed the commits you want to remove, you’ll also need to force push the changes to the remote repository. You can do this with the following command:

git push --force origin <branch-name>

It’s important to note that git reset --hard can be dangerous, as it permanently deletes all commits and changes made after the specified commit. Be sure to back up your changes before running this command.