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


This gives a good explanation of squashing multiple commits:

but it does not work for commits that have already been pushed. How do I squash the most recent few commits both in my local and remote repos?

When I do git rebase -i origin/master~4 master, keep the first one as pick, set the other three as squash, and then exit (via c-x c-c in emacs), I get:

$ git rebase -i origin/master~4 master
# Not currently on any branch.
nothing to commit (working directory clean)

Could not apply 2f40e2c… Revert “issue 4427: bpf device permission change option added” $ git rebase -i origin/master~4 master Interactive rebase already started

where 2f40 is the pick commit. And now none of the 4 commits appear in git log. I expected my editor to be restarted so that I could enter a commit message. What am I doing wrong?


Squash commits locally with:

git rebase -i origin/master~4 master

where ~4 means the last 4 commits.

This will open your default editor. Here, replace pick in the second, third, and fourth lines (since you are interested in the last 4 commits) with squash. The first line (which corresponds to the newest commit) should be left with pick. Save this file.

Afterwards, your editor will open again, showing the messages of each commit. Comment the ones you are not interested in (in other words, leave the commit message that will correspond to this squashing uncommented). Save the file and close it.

You will than need to push again with the -f flag.

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).

How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?

git error: failed to push some refs to remote