How Do I Squash My Last N Commits Together?

Better Stack Team
Updated on June 24, 2024

To squash your last N commits together into a single commit, you can use an interactive rebase. Here's how you can do it:

Step 1: Start an Interactive Rebase

 
git rebase -i HEAD~N

Replace N with the number of commits you want to squash, for example, if you want to squash the last 3 commits, use git rebase -i HEAD~3.

This command will open an interactive rebase window in your default text editor.

Step 2: Squash Commits

In the interactive rebase window, you'll see a list of commits starting from the specified commit (HEAD~N). Each commit will be prefixed with the word "pick". To squash commits, change "pick" to "squash" (or "s" for short) for all but the first commit you want to keep unchanged.

For example:

 
pick 1a2b3c4 Commit message 1
squash 5d6e7f8 Commit message 2
squash 9g0h1i2 Commit message 3

Save and close the editor.

Step 3: Edit the Squashed Commit Message (Optional)

After you save and close the editor, Git will open another editor window where you can edit the commit message for the squashed commit. This message will be used for the new squashed commit.

Step 4: Finish the Rebase

Once you've edited the commit message (or if you didn't edit it), save and close the editor. Git will complete the rebase process and squash the specified commits into a single commit.

Note:

  • Interactive rebasing rewrites commit history, so use it with caution, especially if you've already shared your changes with others.
  • After squashing commits, you may need to force-push (git push --force) if you've already pushed the commits to a remote repository.
Got an article suggestion? Let us know
Explore more
Git
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github