How to revert a commit in Git without losing history
· Category: Git
Short answer
Use git revert <commit-hash> to create a new commit that undoes the changes from a specific commit. This preserves history, unlike git reset. If you need to modify the most recent commit instead, see how to amend a Git commit. For applying a single commit elsewhere, see how to cherry-pick a commit in Git.
Steps
- Find the commit hash:
git log --oneline - Revert the commit:
git revert abc1234 - Edit the commit message if prompted, then save
- Push the revert:
git push origin main - Verify the revert with
git logandgit diff
Tips
- Reverting is safe for shared branches because it does not rewrite history
- To revert a merge commit, use
git revert -m 1 <merge-commit-hash> - If a revert causes conflicts, resolve them using how to resolve Git merge conflicts