How to Permanently Delete a Git Commit History Using Revert and Reset
This guide explains why you might need to erase a Git commit, compares git revert and git reset, provides step‑by‑step commands with examples, and shows how to force‑push to remove the unwanted history from both local and remote repositories.
Why Delete Commit History
Sometimes a mistaken commit is pushed to a shared repository and must be removed immediately to avoid exposing sensitive code.
Using git revert to Undo Commits
Purpose : Creates a new commit that reverses the changes of a previous commit while preserving history.
Syntax :
git revert <commit-hash> git revert <commit-hash1> <commit-hash2> ... git revert HEAD git revert <commit-hash1>^..<commit-hash2>Example: b1b56b50a0859556623283946972e495d4a42fc1 Run the command:
git revert b1b56b50a0859556623283946972e495d4a42fc1Git opens the default editor (e.g., vim) to edit the revert commit message. After saving and exiting, push the changes: git push The revert removes the changes but the original commit remains in the history.
Using git reset to Erase Commits
Purpose : Moves the HEAD pointer and optionally modifies the index and working directory, allowing you to delete commits entirely.
Common Forms : git reset --soft HEAD~1 Keeps changes staged for a new commit. git reset HEAD~1 Unstages changes but keeps them in the working directory. git reset --hard HEAD~1 Discards all changes, resetting the working tree to the previous commit. git reset --hard <commit-hash> After resetting locally, the remote still contains the unwanted commits. To delete them from the remote, force‑push the cleaned history: git push --force or equivalently:
git push origin <branch-name> --forceImportant Warning
Using --force overwrites the remote repository’s history. This operation is dangerous and should only be performed when you are certain that the local and remote branches are synchronized and that no other collaborators rely on the removed commits.
Summary
git revertcreates a new commit that undoes changes while preserving history; git reset moves the branch pointer and can delete commits, especially when combined with git push --force to rewrite remote history.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
