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

This gives a good explanation of squashing multiple commits:

http://git-scm.com/book/en/Git-Branching-Rebasing

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?

EDIT: 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 cx cc 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

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 (eg git push origin +master to force a push to the master branch).


在一个分支上,我能够像这样做(最后4次提交)

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

A lot of problems can be avoided by only creating a branch to work on & not working on master :

git checkout -b mybranch

The following works for remote commits already pushed & a mixture of remote pushed commits / local only commits:

# example merging 4 commits

git checkout mybranch
git rebase -i mybranch~4 mybranch

# at the interactive screen
# choose fixup for commit: 2 / 3 / 4

git push -u origin +mybranch

I also have some pull request notes which may be helpful.

链接地址: http://www.djcxy.com/p/1354.html

上一篇: 功能分支重新绑定后,Git推送被拒绝

下一篇: 如何压扁git后提交git?