How do I squash my last N commits together with Git?

To squash your last N commits into a single commit in Git, follow these steps:

Step-by-Step Guide

  1. 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`)
  1. In the interactive editor:
  • For the commits you want to squash, replace pick with squash (or s).
  • 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)
  1. Edit the new commit message:
  • Delete or combine the existing commit messages into one meaningful message.
  • Save and close the editor.
  1. Resolve conflicts (if any):
  • Fix conflicts, then run:
    bash git add . && git rebase --continue
  1. Force-push (if the commits were already pushed to a remote):
   git push --force  # ⚠️ Use with caution on shared branches!

Example Workflow

  1. 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
  1. 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 (use f instead of s).
  • 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!

Leave a Reply

Your email address will not be published. Required fields are marked *