How can I combine two commits into one commit?
This question already has an answer here:
You want to git rebase -i
to perform an interactive rebase.
If you're currently on your "commit 1", and the commit you want to merge, "commit 2", is the previous commit, you can run git rebase -i HEAD~2
and change the first word of the second line from "pick" to "squash". Then write your file, and quit. Git will squash your first commit into your second last commit.
Note that this process rewrites the history of your branch. If you are pushing your code somewhere, you'll have to git push -f
and anybody sharing your code will have to jump through some hoops to pull your changes.
Note that if the two commits in question aren't the last two commits on the branch, the process will be slightly different.
Lazy simple version for forgetfuls like me:
git rebase -i HEAD~3
or however many commits instead of 3.
Turn this
pick YourCommitMessageWhatever
pick YouGetThePoint
pick IdkManItsACommitMessage
into this
pick YourCommitMessageWhatever
s YouGetThePoint
s IdkManItsACommitMessage
and do some action where you hit esc
then enter
to save the changes. [1]
When the next screen comes up, get rid of those garbage # lines [2] and create a new commit message or something, and do the same escape
enter
action. [1]
Wowee, you have fewer commits. Or you just broke everything.
[1] - or whatever works with your git configuration. This is just a sequence that's efficient given my setup.
[2] - you'll see some stuff like # this is your n'th commit
a few times, with your original commits right below these message. You want to remove these lines, and create a commit message to reflect the intentions of the n commits that you're combining into 1.
git rebase -i HEAD~<quantity of your commits>
(ie git rebase -i HEAD~5
) txt
file change pick
keyword to squash
for all commits, except first commit (which is on the top). For top one change it to reword
(which means you will provide a new comment for this commit in the next step) and click SAVE! 下一篇: 我如何将两个提交合并为一个提交?