Rewrite history

2 snippets in Git

GitGit

Interactive Rebase

Git · Rebasing
Syntax
git rebase -i HEAD~<n>
git rebase -i <commit>
Example
# Rewrite the last 4 commits:
git rebase -i HEAD~4

# Editor opens with:
# pick a1b2c3d Add login page
# pick d4e5f6a Add signup page
# pick b7c8d9e Fix typo in login
# pick c0d1e2f Update styles
#
# Change 'pick' to: squash, reword, edit, drop, etc.

Note Commands: pick (keep as-is), reword (change message), squash (merge into previous commit), fixup (squash but discard message), edit (pause to modify), drop (delete commit). Save and close the editor to execute.

Rewrite Repository History (git-filter-repo)

Git · Advanced
Syntax
git filter-repo --path <path-to-keep>
git filter-repo --invert-paths --path <path-to-remove>
Example
# Remove a file from entire history (e.g., accidentally committed secret):
git filter-repo --invert-paths --path secrets.env

# Extract a subdirectory into its own repo:
git filter-repo --path src/auth/

Note WARNING: This rewrites ALL commit hashes. Every collaborator must re-clone. git-filter-repo is a separate tool (pip install git-filter-repo) that replaces the deprecated git filter-branch. Back up your repo before using this.

Frequently asked questions

How does Git handle rewrite history?
Git covers this with 2 copy-ready snippets on this page. The "Interactive Rebase" snippet in Git uses `git rebase -i HEAD~<n>`.
Which command does the Git example use?
The "Interactive Rebase" snippet uses `git rebase -i HEAD~<n>`, from the Rebasing section of the Git cheat sheet.
What other Git snippets are shown for "rewrite history"?
Besides "Interactive Rebase", this page also shows "Rewrite Repository History (git-filter-repo)".
Is there anything to watch out for?
Yes. For "Interactive Rebase": Commands: pick (keep as-is), reword (change message), squash (merge into previous commit), fixup (squash but discard message), edit (pause to modify), drop (delete commit). Save and close the editor to execute.