git rebase 简介

1,107 阅读2分钟

前言

使用场景

主要功能是编辑git提交历史,所以建议在私有分支使用!

rebase使用方法

1. 开始变基

git rebase -i master (不一定对比分支,也可以对比某个提交点)

执行命令后出现提交历史:

pick 4daa490d 1
pick a996b550 ar
pick 2b43e8b1 2
pick 8e71f26f as
pick 37817519 3
pick 876680bd af
pick 8ddef852 4
pick 631d56b5 ad
pick 4814d62b 5

2. 进行修改

往下拉会看见命令提示:

# 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 <commit> = like "squash", but discard this commit's log message
# x, exec <command> = run command (the rest of the line) using shell
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]

解释一下上面的命令:(完整提交 = 提交内容 + 提交日志)

pick:该提交保留
reword:提交内容不变,但是编辑提交日志
squash:提交内容和提交日志合并至上次提交(提交日志合并时可编辑)
fixup:提交内容合并至上次提交,提交日志不合并(删除提交日志)
drop:删除本次提交内容和提交日志

单独说一下edit这个命令:

回滚至当次提交(未提交状态,保留提交内容)
然后你可以修改当次提交内容,可以添加或者拆分提交!(月光宝盒时光倒流功能)
修改完毕后执行:git rebase --continue

3. 测试结果

假设修改设置如下:

pick 4daa490d 1
reword a996b550 ar
pick 2b43e8b1 2
squash 8e71f26f as
pick 37817519 3
fixup 876680bd af
pick 8ddef852 4
drop 631d56b5 ad
pick 4814d62b 5

最终效果:

4daa490d 1
a996b550 ar reword
2b43e8b1 2 as squash
37817519 3
8ddef852 4
4814d62b 5

备用方案

git merge --squash dev

--squash选项作用:合并后不自动提交,相当于用分支的文件覆盖当前主干的文件

优点:主干提交记录非常干净。

缺点:丢失分支提交记录。

后语

建议大家多实践测试,才能理解透彻该命令的使用方法!

推荐使用图形工具进行操作,方便又不容易出错!