How to Delete Git Commit History Using git revert and git reset
This article explains why and how to remove unwanted Git commit history by using git revert to create a compensating commit, git reset to move the HEAD pointer, and git push --force to overwrite the remote repository, with step‑by‑step commands and safety tips.
The author, a senior architect, discovered an accidental commit that needed immediate removal from the remote repository to avoid exposing sensitive changes.
Why Delete Commit History
Accidental commits are visible to everyone in the remote repository; deleting them quickly prevents others from seeing the mistake.
Using git revert to Undo Commits
Purpose: git revert creates a new commit that reverses the changes of a previous commit while preserving history.
Syntax
Undo a single commit:
git revert <commit-hash>Undo multiple commits:
git revert <commit-hash1> <commit-hash2> ...Undo the latest commit:
git revert HEADUndo a range of commits:
git revert <commit-hash1>^..<commit-hash2>After running git revert , Git opens the default editor (e.g., Vim) to edit the revert commit message; the user saves and exits, then pushes the new commit.
Using git reset to Remove Commits
Purpose: git reset moves the HEAD pointer and can modify the index and working tree, allowing you to discard commits entirely.
Syntax
Undo the last commit but keep changes staged:
git reset --soft HEAD~1Undo the last commit and unstage changes:
git reset HEAD~1Undo the last commit and discard all changes:
git reset --hard HEAD~1Move HEAD to a specific commit (discard later history):
git reset --hard <commit-hash>In the example, the author resets the local branch two commits back with git reset HEAD~2 , restoring the code to the state before the erroneous commits.
Force‑Pushing to Remote
Since the remote still contains the unwanted commits, the author overwrites the remote history with the cleaned local state using:
git push --forceor the explicit form:
git push origin <branch-name> --forceImportant Tip: Using --force rewrites remote history and can be dangerous; ensure the local and remote codebases are compatible before proceeding.
Summary
git reset moves the branch pointer and can modify history without creating a new commit, while git revert creates a new commit that undoes previous changes, preserving history. Combining git reset with git push --force allows complete removal of unwanted commits from both local and remote repositories.
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.