kingBook

导航

git rebase 合并多个commit

更多参考:https://zhuanlan.zhihu.com/p/139321091


进入 rebase:

  • git rebase -i <commit_sha>: 如 git rebase -i 98c8935 ,列出 98c8935 之后的所有提交
  • git rebase -i HEAD~<id>: 如 git rebase -i HEAD~3 ,列出最后的3个提交
  • git rebase -i --root: 将列出所有提交

进入 rebase 后不要使用鼠标,用以下快捷键:

  • Insert 进入插入模式
  • ←↑→↓ 方向键移动光标
  • Delete 或 BackSpace 键删除文字
  • Ctrl+C 退出插入文本模式

在 rebase 里修改:

  • 选择ppick指令,git会应用这个提交,以同样的提交信息(commit message)保存提交
  • 选择rreword指令,git会应用这个提交,但需要重新编辑提交信息
  • 选择eedit指令,git会应用这个提交,但会因为amending而终止
  • 选择ssquash指令,git会应用这个提交,但会与之前的提交合并
  • 选择ffixup指令,git会应用这个提交,但会丢掉提交日志

Ctrl+C 退出插入模式后,输入以下命令退出 rebase(输入 : 时需要按住 Shift):

  • :wq 保存文件并退出
  • :wq! 强制保存文件,并退出
  • :q 不保存文件,退出
  • :q! 不保存文件,强制退出

例:

  1. 以单行的形式显示提交历史
$ git log --oneline
72c49d7 (HEAD -> master) a3
013e497 a2
25cc223 a1
6335195 a0
16024c1 create
  1. 现在要把 a0,a1,a2,a3 合并成一个提交 a,执行以下命令进入rebase,操作最近的4个提交
$ git rebase -i HEAD~4
pick 6335195 a0
pick 25cc223 a1
pick 013e497 a2
pick 72c49d7 a3
  1. 在 rebase 模式下修改
  • 按 Insert 进入插入文本模式,
  • ←↑→↓ 方向键移动光标
  • Delete 或 BackSpace 键删除文字
  • Ctrl+C 退出插入文本模式
  • 用以上操作方法修改如下:
pick 6335195 a0
s 25cc223 a1
s 013e497 a2
s 72c49d7 a3
  1. 修改之后 Ctrl+C 退出插入文本模式,然后输入 :wq 按回车键保存并退出(输入 : 时需要按住 Shift),
    出现如下,要求修改提交信息
# This is a combination of 4 commits.
# This is the 1st commit message:

a0

# This is the commit message #2:

a1

# This is the commit message #3:

a2

# This is the commit message #4:

a3
  1. 使用步骤3的操作方法,修改备注信息,其中"#"表示注释可以不管,此处修改为 "a" 把其它删除,如下:
# This is a combination of 4 commits.
# This is the 1st commit message:

a

# This is the commit message #2:

# This is the commit message #3:


# This is the commit message #4:
  1. 修改之后和步骤4一样(Ctrl+C 退出插入文本模式,然后输入 :wq 按回车键保存并退出),显示合并完成提示,如下:
[detached HEAD b932448] a
 Date: Thu Nov 4 23:52:17 2021 +0800
 2 files changed, 16 insertions(+), 1 deletion(-)
Successfully rebased and updated refs/heads/master.
  1. 可以使用git loggit log --oneline 查看合并后的提交历史列表
$ git log --oneline
b932448 (HEAD -> master) a
16024c1 create

posted on 2018-04-27 11:58  kingBook  阅读(267)  评论(0编辑  收藏  举报