How to squash commits in git after they have been pushed? How to squash commits in git after they have been pushed? git git

How to squash commits in git after they have been pushed?


Squash commits locally with

git rebase -i origin/master~4 master

and then force push with

git push origin +master

Difference between --force and +

From the documentation of git push:

Note that --force applies to all the refs that are pushed, hence using it with push.default set to matching or with multiple push destinations configured with remote.*.push may overwrite refs other than the current branch (including local refs that are strictly behind their remote counterpart). To force a push to only one branch, use a + in front of the refspec to push (e.g git push origin +master to force a push to the master branch).


On a branch I was able to do it like this (for the last 4 commits)

git checkout my_branchgit reset --soft HEAD~4git commitgit push --force origin my_branch


Minor difference to accepted answer, but I was having a lot of difficulty squashing and finally got it.

$ git rebase -i HEAD~4
  • At the interactive screen that opens up, replace pick with squashat the top for all the commits that you want to squash.
  • Save and close the editor

Push to the remote using:

$ git push origin branch-name --force