How to Squash Multiple Commits Into One with Git

How to Squash Multiple Commits Into One with Git


This is an awesome feature of rebase that can be used in the interactive mode. To squash the last n commits into one, run the following command:

git rebase -i HEAD~n

That will open up a text-editor with something similar to the following:

pick commit_1
pick commit_2
pick commit_3
pick commit_n
# Bunch of comments

Leave the first commit alone, and change the rest of the picks to squash. Save and exit the editor.

So if you wanted to squash the last three commits, you’ll first run git rebase -i HEAD~3 and then you’ll want to edit your commits to look something like this:

pick dd661ba Commit 1
squash 71f5fee Commit 2
squash f4b4bf1 Commit 3

If you’ve already pushed to a remote before squashing your commits, you’ll have to push to the remote again, with the -f flag, otherwise git will throw an error at you.

It is strongly suggested that you read the information in the opened file as there are many things you can do.


i’ve tried everything to save and close the editor but nothing happens so far, CTRL+O,CTRL+X,CTRL+G, the only command that worked was CTRL+Z and it stopped the editor and once i tried $git -rebase --continue (due this was the recommended action) it said that it had a merge conflict with my first commit. So i need help


What editor was that?

As for the conflict, you will need to find it. does it not tell you where it is?
I personally use atom and it has a plugging that allows me to easily find the merging conflicts. You could try something similar with your editor of choice.


It’s Vim editor. You need press “i” to Insert words, “esc” back to normal mode, “:wq”, save and exit, “:q!” quit without save. For more tips ,you may go to google Vim basic.


It’s Vim editor. You need to know some basic commands to use it.


git rebase master
would rebase all your latest commits on the current branch from the master branch.
Merging the branch after giving this command would help to maintain the linear commit history