Git Rebase 命令详解
什么是 git rebase?
git rebase 是 Git 中用于整合分支的另一种方法(替代 git merge)。它的核心思想是将当前分支的提交“重新应用”到目标分支的最新提交之上,从而使提交历史呈现线性化,避免合并提交(merge commit)。
核心流程(图示)
1. Rebase 前状态:
假设有两个分支:
master分支:提交A → B → Cfeature分支:从B分叉,提交D → E
gitGraph
commit id: "A"
commit id: "B"
branch feature
commit id: "D"
commit id: "E"
checkout main
commit id: "C"
2. 执行 git rebase master:
在 feature 分支上运行 git rebase master,会:
- 将
feature的提交D和E临时保存。 - 将
feature分支的基点从B更新到master的最新提交C。 - 将
D和E重新应用到C之后,生成新提交D'和E'。
gitGraph
commit id: "A"
commit id: "B"
commit id: "C"
branch feature
commit id: "D'"
commit id: "E'"
Rebase 的核心操作
1. 基础用法:
# 当前在 feature 分支
git checkout feature
git rebase master
2. 交互式 Rebase(修改提交历史):
git rebase -i HEAD~3 # 修改最近 3 个提交(如合并、重写提交信息等)
Rebase 解决冲突
- 冲突发生:在 rebase 过程中,如果某个提交与目标分支冲突,Git 会暂停并提示解决冲突。
- 手动解决冲突:编辑文件后标记为已解决:
git add <冲突文件> git rebase --continue # 继续 rebase - 终止 Rebase:
git rebase --abort # 放弃 rebase,回到原始状态
Rebase vs Merge
| 操作 | 提交历史 | 合并提交 | 适用场景 |
|---|---|---|---|
git merge | 保留分支结构,生成合并提交 | 是 | 公共分支(如多人协作) |
git rebase | 线性历史,无合并提交 | 否 | 私有分支(需整理本地提交历史) |
注意事项
- 不要对公共分支使用 rebase:改写历史会导致协作混乱。
- 远程分支:本地 rebase 后需强制推送(
git push -f),但需谨慎使用。 - 黄金法则:只对尚未共享的本地提交使用 rebase!
示例流程
-
初始状态:
gitGraph commit id: "A" commit id: "B" branch feature commit id: "D" checkout main commit id: "C" -
执行
git rebase main:gitGraph commit id: "A" commit id: "B" commit id: "C" branch feature commit id: "D'"
通过 git rebase,你可以让代码提交历史更清晰、更易读!