6. 交互式变基

交互式变基是指在使用 git rebase 命令进行变基时,可以使用 -i 选项通过文本编辑器对变基后的即将插入新位置的提交进行重新编辑并提交的操作。

这个操作包括

  1. pick:使用提交。
  2. squash:合并到前一个提交。
  3. fixup:类似squash,但丢弃提交信息。
  4. reword:使用提交,但重新编辑提交信息。
  5. edit:使用提交,暂停修改。
  6. drop:删除提交

示例

现在有这样一组分支。

A---B---C---D---E---F---G  master

下载此示例仓库

现在希望在 D 位置变基到 B 位置。变基后 C 提交对象删除。变基时 DE 合并为 DE'F 删除,G 的提价信息由原来的 G 体改为 G for rebase。

变基前提交信息

weimingze@mzstudio:~/rebase/rebase_demo4$ git log --graph --oneline --all
* 8498821 (HEAD -> master) G
* 18b5f87 F
* 0aee6a4 E
* 6753c83 D
* 2052505 C
* 95a244a B
* 297e5a2 A

使用 git rebase -i --onto HEAD~5 HEAD~4 命令进行交互式变基。编辑器提示如下:

pick 6753c83 D
pick 0aee6a4 E
pick 18b5f87 F
pick 8498821 G

# Rebase 2052505..8498821 onto 95a244a (4 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup [-C | -c] <commit> = like "squash" but keep only the previous
...

编辑器中 # 开头的内容是注释内容,提示你如何操作。最上面的四行是 DEFG 四个提交的的提交方式,默认是 pick 使用提交。

我们可以根据目标,修改上述内容如下:

pick 6753c83 D
squash 0aee6a4 E
drop 18b5f87 F
reword 8498821 G

其中 pick 6753c83 D 是提交 D

squash 0aee6a4 E 是将 E 和上一次提交合并。此提交回弹出编辑器用来编辑两个提交合并后的提交信息。此时我们重新编辑提交信息为 DE' for D and E Merge

drop 18b5f87 F 是删除 F 提交。

reword 8498821 G 会调用编辑器,重新编辑 G 的提交信息,再次我们添加提交信息: G for rebase。

保存退出上述编辑器。

执行结果如下:

weimingze@mzstudio:~/rebase/rebase_demo4$ git rebase -i --onto HEAD~5 HEAD~4
[detached HEAD 536f3d4] DE` for D and E Merge
 Date: Tue Jan 20 15:40:54 2026 +0800
 2 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 d.txt
 create mode 100644 e.txt
[detached HEAD b2cfb81] G for rebase。
 Date: Tue Jan 20 15:40:54 2026 +0800
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 g.txt
Successfully rebased and updated refs/heads/master.
weimingze@mzstudio:~/rebase/rebase_demo4$ git log --graph --oneline --all
* b2cfb81 (HEAD -> master) G for rebase。
* 536f3d4 DE` for D and E Merge
* 95a244a B
* 297e5a2 A

通过上述操作,我们将原来的分支修改为如下结构:

A---B---DE'---G  master

实验

使用交互式变基的方式对示例中的提交进行操作。