可以使用git rebase
合并commit,用法为
git rebase -i [startpoint] [endpoint]
其中-i
为--interactive
,即通过交互界面完成合并操作。[startpoint]
和[endpoint]
为需要合并的起止版本号,其中[startpoint]
不会被进入合并流程,而[endpoint]
则会(当然可以选择不合并)。
需要确保该分支只有你自己在使用时才使用rebase进行合并!
示例
通过git log
查看commit的版本号,假设a5~a1
依次如下:
70b1648 (HEAD -> master) a5
cef63d7 a4
2373978 a3
2413975 a2
98be6d0 a1
需要合并a2、a3、a4
,则使用命令([endpoint]
省略时默认为HEAD
):
git rebase -i 98be6d0
然后会出现一个文件编辑的界面
pick 2413975 a2
pick 2373978 a3
pick cef63d7 a4
pick 70b1648 a5
...
注意这里需要留头留尾,即首尾都需要pick
,否则会出现head detached
等情况。这也是为什么我们在这里的[endpoint]
要设置为HEAD
。
我们修改上方的指令即可,下方主要为命令具体说明,其中s
即为squash
,可以将几个commit合并,将文件修改为:
pick 2413975 a2
s 2373978 a3
s cef63d7 a4
pick 70b1648 a5
这样就将a3,a4
的提交都折叠了。输入:wq
保存后会进入新的编辑界面:
# This is a combination of 3 commits.
# This is the 1st commit message:
a2
# This is the commit message #2:
a3
# This is the commit message #3:
a4
可以将其删除,输入自己想要的合并信息如:
# This is a combination of 3 commits.
a24
然后输入:wq
保存即可。
此时git log --oneline
查看提交记录则变成了
c7b2cce (HEAD -> master) a5
478b208 a24
98be6d0 a1
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…