How to squash Git commits already pushed to repository

If you have several commits and want to merge them (squash) into one, you can do that by squashing them, even if you already pushed them to your remote repository.

To do that, first you need to list your commits with the following command:

In the list, search for the last commit you want to merge with the others and take the one after it. For example, in the following result:

Tap  q to quit this view

I would like to merge from the first one until the “message 5” commit, then I will have to use the id from the commit “message 7” in the following command line to start a rebase:

This will open the editor, starting with the commits list, and followed by some commands you can use:

If you want, you can also rename your commits here like if you were doing an amend.

You will then have to replace the  pick commands by  squash commands (or s) for the lines you want to merge, except for the first one. When you’re finished, save the file  echap + ':wq'.

In some case, you will maybe have conflicts, you will have to resolve them before being able to continue. Don’t forget, after you’ve resolved them you need to do a  git rebase --continue .

Now, just finish by pushing this to your remote repository. If you already pushed those commits to your repository, you will have to force the push (option -f).

Read more on Git website: 7.6 Git Tools – Rewriting History