To squash your last N commits into a single commit in Git, follow these steps:
Step-by-Step Guide
- Start an interactive rebase for the last
N
commits:
git rebase -i HEAD~N # Replace `N` with the number of commits to squash (e.g., `3`)
- In the interactive editor:
- For the commits you want to squash, replace
pick
withsquash
(ors
). - Keep the oldest commit as
pick
(it will become the base for the squashed commit). - Example for squashing 3 commits:
pick a1b2c3d Commit 1 (oldest) squash d4e5f6 Commit 2 squash g7h8i9 Commit 3 (newest)
- Edit the new commit message:
- Delete or combine the existing commit messages into one meaningful message.
- Save and close the editor.
- Resolve conflicts (if any):
- Fix conflicts, then run:
bash git add . && git rebase --continue
- Force-push (if the commits were already pushed to a remote):
git push --force # ⚠️ Use with caution on shared branches!
Example Workflow
- Squash the last 2 commits:
git rebase -i HEAD~2
- In the editor:
pick abc123 Add login form squash def456 Fix typo
- Save and update the commit message to:
Add login form with typo fix
- Result:
- The two commits are merged into one with the new message.
Key Notes
squash
vs.fixup
:squash
: Combines commit messages.fixup
: Discards intermediate messages (usef
instead ofs
).- Undo Mistakes: Use
git reflog
to recover from accidental rebases. - Shared Branches: Avoid force-pushing (
--force
) on branches others are using.
By squashing commits, you maintain a clean and concise Git history!