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

  1. Find the commit hash: git log --oneline
  2. Revert the commit: git revert abc1234
  3. Edit the commit message if prompted, then save
  4. Push the revert: git push origin main
  5. Verify the revert with git log and git 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