How can I combine 2 'git commit's

I have made 2 'git commit' locally. But I have not pushed, is it possible for me to edit my git and combine those 2 git commit into 1?


Yes it is possible:

You have to first find the commit that is before the ones you want to work with. Imagine we want to combine last two commits:

git rebase -i HEAD~3

This will fire up an editor for interactive rebase that is giving you a possibility to perform so called squashing of the commits and it will list commits starting from one that is three commits ago.

PLEASE, read the help message in the fired up editor window to understand how to use interactive rebase. In order to cancel rebase operation you have to delete all lines from the file and save it ! You also don't touch the commit ID and description - you just change the command before the commit ID from pick to "s" (squash)

Another thing is that you absolutely correctly mentioned that you didn't push yet. First and only one rule of git is "Do not rewrite published history". Ie you don't rebase, reorder or delete commits that were already pushed for public access. This is true for all situation except when you're the only one who works on the project.


If you've made a commit and want to add some changes to it, you can use git commit --amend which will amend your last commit. If you want to do this without going through all the trouble of git rebasing then:

git checkout --soft HEAD~

This will remove the last commit without removing the changes and then

git commit --amend -C HEAD

which will modify the latest commit with the new changes in the index. The -C HEAD flags take the commit message from the head commit, so you don't even need to add the message again.


还有另一篇关于压扁的文章:http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html

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

上一篇: 如何加入最后的N个合并提交到一个?

下一篇: 我该如何结合2'git commit