参考:https://segmentfault.com/a/1190000007748862

需求

当前状态:

$ git log --oneline --all --graph
* 69edf65 (HEAD -> main, origin/main) Update update-markdown-to-wordpress.py
* a6f3b81 Update README.md
* bf4d1f0 Update README.md
* 50c405f Update README.md
* 4a5004d Add README.md

现在我想要合并三个Update README.md,然后再提交Update update-markdown-to-wordpress.py。

操作

首先将HEAD指向最近的Update README.md:git reset --soft HEAD~1

暂存当前修改:git stash

用rebase修改从4a5004d的提交到当前HEAD的提交:git rebase -i 4a5004d,进入vim修改界面:

pick 50c405f Update README.md
pick bf4d1f0 Update README.md
pick a6f3b81 Update README.md

将下面两个pick改成s,如下:

pick 50c405f Update README.md
s bf4d1f0 Update README.md
s a6f3b81 Update README.md

输入 :wq 保存退出。

进入以下界面:

# This is a combination of 3 commits.
# This is the 1st commit message:

Update README.md

# This is the commit message #2:

Update README.md

# This is the commit message #3:

Update README.md

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date:      Sun Nov 21 18:17:10 2021 +0800
#
# interactive rebase in progress; onto 4a5004d
# Last commands done (3 commands done):
#    squash bf4d1f0 Update README.md
#    squash a6f3b81 Update README.md
# No commands remaining.
# You are currently rebasing branch 'main' on '4a5004d'.
#
# Changes to be committed:
#       modified:   README.md
#

不用改,直接输入 :wq 保存退出。

当前状态:

$ git log --oneline --all --graph
* 9075fcc (HEAD -> main) Update README.md
| *   abfbc6b (refs/stash) WIP on main: a6f3b81 Update README.md
| |\
| | * fa40b4c index on main: a6f3b81 Update README.md
| |/
| | * 69edf65 (origin/main) Update update-markdown-to-wordpress.py
| |/
| * a6f3b81 Update README.md
| * bf4d1f0 Update README.md
| * 50c405f Update README.md
|/
* 4a5004d Add README.md

$ git log --oneline --graph
* 9075fcc (HEAD -> main) Update README.md
* 4a5004d Add README.md
* 487cb78 Initial commit

然后git stash pop还原一下,然后再提交Update update-markdown-to-wordpress.py即可。

总结

总结一下全过程:

git reset --soft <commid_id> #<commid_id>为rebase的"终点"提交

git stash #如果当前有未提交的修改

git rebase -i <commid_id> #<commid_id>为rebase的"起点"提交的前一个
# 进入vim界面,最靠前的那个pick不要改,之后的所有pick全部改成s,保存退出;进入vim界面,再次保存退出

git stash pop

注意:

  • 进入vim界面,最靠前的一次pick不要改。

  • git rebase -i <commit_id>中的是真正要合并的commit的起点的前一个