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 d4e5f6g Add signup page
# pick h7i8j9k Fix typo in login
# pick l0m1n2o 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.