git
squash
commit
How do I squash my last N commits together?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
To squash the last N commits together in Git, you can use an interactive rebase. This process allows you to combine multiple commits into a single commit. Here’s how you can do it:
Steps to Squash Last N Commits
- Start an Interactive Rebase:Run the following command to start an interactive rebase for the last N commits:
Replace N with the number of commits you want to squash. For example, if you want to squash the last 3 commits, use:
- Mark Commits for Squashing:After running the rebase command, an editor will open showing a list of the last N commits. It will look something like this:
- The first commit should remain as
pick. - For the commits you want to squash into the first one, replace
pickwithsquash(or simplys).
For example:
This tells Git to squash the second and third commits into the first one.
- Save and Close the Editor:After making your changes, save and close the editor. In Vim, you would press
Esc, type:wq, and then pressEnter. - Combine Commit Messages (Optional):After squashing, another editor window may open, allowing you to edit the commit message for the combined commit. You can choose to edit, combine, or replace the commit messages.
- The default behavior is to concatenate all the commit messages.
- You can modify this as needed. Save and close the editor when you’re done.
- Force Push to Remote (If Necessary):If you’ve already pushed these commits to a remote repository, you’ll need to force push the changes to update the remote branch:
Replace <branch-name> with the name of your branch.
Example Workflow
Let’s say you want to squash the last 3 commits on the main branch:
- Start the rebase:
- Edit the rebase instructions:Change it from:
To:
- Save and close the editor.
- Edit the combined commit message if needed, then save and close the editor.
- Force push if the branch was previously pushed:
Summary
git rebase -i HEAD~N: Start an interactive rebase for the last N commits.- Mark commits with
squash: Changepicktosquashfor the commits you want to combine. - Force push: Use
git push --forceto update the remote branch if necessary.
By following these steps, you can successfully squash your last N commits into a single, cleaner commit.

