How to Rewrite Git History: Commands and Examples
To rewrite git history, use
git commit --amend to change the last commit or git rebase -i to edit multiple past commits. These commands let you modify commit messages, combine commits, or remove commits safely before pushing.Syntax
git commit --amend: Changes the most recent commit by adding new changes or editing the commit message.
git rebase -i <commit>: Opens an interactive editor to rewrite commits starting after the specified commit. You can edit, reorder, squash, or remove commits.
bash
git commit --amend
git rebase -i HEAD~3Example
This example shows how to change the last commit message and then how to squash the last two commits into one.
bash
# Change last commit message $ git commit --amend -m "Updated commit message" # Start interactive rebase for last 2 commits $ git rebase -i HEAD~2 # In the editor, change 'pick' to 'squash' for the second commit # Save and close the editor to combine commits
Output
Successfully amended the commit message.
Rebasing (1/2) - commit combined successfully.
Common Pitfalls
- Rewriting commits that have been pushed to shared repositories can cause conflicts for others.
- Always backup or create a branch before rewriting history.
- Using
git rebase -iincorrectly can lose commits if you delete lines accidentally.
bash
## Wrong: rewriting pushed commits without coordination $ git rebase -i HEAD~3 # force push without informing team $ git push --force ## Right: create a backup branch before rewriting $ git branch backup-branch $ git rebase -i HEAD~3 $ git push --force-with-lease
Quick Reference
| Command | Purpose |
|---|---|
| git commit --amend | Edit the last commit message or content |
| git rebase -i HEAD~N | Interactively rewrite last N commits |
| git push --force-with-lease | Force push safely after rewriting history |
| git reflog | Recover lost commits after rewriting |
Key Takeaways
Use git commit --amend to fix the last commit quickly.
Use git rebase -i to rewrite multiple past commits interactively.
Avoid rewriting commits that others have already pulled without coordination.
Always create a backup branch before rewriting history.
Use git push --force-with-lease to safely update remote history.