
Learn how to revert to a previous commit in Git. This guide covers git reset, git revert, and git checkout to safely undo changes. Sometimes, you may need to undo changes and revert your project to a previous commit in Git.
This guide explains different methods to get the job done so without any further due lets dive in.
Table of Contents
Methods to Revert to a Previous Commit
There are multiple ways to revert to a previous commit in Git and below are 3 methods to revert to a previous commit in Git.
The method you choose depends on whether you want to keep a record of the revert or completely erase changes. Below are the most commonly used techniques:
1. Using git reset (Moves HEAD and Deletes History)
If you want to completely remove commits and reset your branch to a previous commit:
git reset --hard <commit-hash>
--hard
: Removes all changes after the specified commit.--soft
: Keeps changes staged but moves HEAD back.--mixed
: Unstages changes but keeps them in the working directory.
Example:
git reset --hard abc123
This resets the repository to the commit with hash abc123
and deletes all later commits.
⚠️ Warning: This will remove changes permanently unless backed up.
2. Using git revert (Creates a New Commit)
If you want to undo changes but keep a record of them, use:
git revert <commit-hash>
This creates a new commit that negates the changes from the specified commit.
Example:
git revert abc123
This adds a new commit that reverses abc123
, keeping project history clean.
3. Using git checkout (Temporary Switch to an Older Commit)
If you only need to view or test a previous commit:
git checkout <commit-hash>
To return to the latest commit:
git checkout main
4. Using git reflog to Recover Lost Commits
If you reset your branch and lost commits, you can recover them:
git reflog
Find the lost commit’s hash and use:
git reset --hard <commit-hash>
Conclusion
Reverting to a previous commit in Git can be done safely using git reset
, git revert
, or git checkout
. Choose the method that best suits your needs to avoid data loss while maintaining project integrity.
Read our last article of How to comment out multiple lines in python.