How Do I Revert a Git Repository to a Previous Commit?

Better Stack Team
Updated on June 24, 2024

To revert a Git repository to a previous commit, you have a couple of options depending on your needs. Here are two common methods:

Method 1: Using git reset and git push (For Local Changes Only)

If you want to revert to a previous commit and discard any commits made after that, you can use git reset:

 
git reset --hard <commit-id>

Replace <commit-id> with the identifier (hash) of the commit you want to revert to. This command will reset your local repository to the specified commit, discarding any changes made after that commit.

If you've already pushed the changes to a remote repository, you'll also need to force-push the changes to update the remote repository:

 
git push --force

Method 2: Using git revert (For Shared Repositories)

If you've already pushed the commits you want to revert and want to maintain a clean history without rewriting it, you can use git revert:

 
git revert <commit-id>

Replace <commit-id> with the identifier of the commit you want to revert. This command will create a new commit that undoes the changes introduced by the specified commit.

After reverting the commit locally, you can push the changes to the remote repository as usual:

 
git push

Note:

  • Method 1 (git reset) is more aggressive as it rewrites history, which can cause issues if the changes have already been shared with others.
  • Method 2 (git revert) is safer for shared repositories as it creates a new commit to undo the changes, preserving the commit history.
  • When using git reset --hard, be cautious as it will discard any uncommitted changes and staged files.
  • Always communicate with your team if you're reverting changes in a shared repository to avoid conflicts and confusion.

Choose the method that best fits your situation and requirements, and ensure you understand the implications, especially if you're working in a collaborative environment.

Got an article suggestion? Let us know
Explore more
Git
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github