git rebase 变基操作
git rebase 将分支的提交重新应用到另一个分支上,使历史保持线性。
什么是 rebase
rebase(变基)将当前分支的提交"移植"到目标分支的最新提交之后。
rebase vs merge
Bash
merge 合并:
A → B → C → M
↗
D → E
rebase 变基:
A → B → C → D' → E'
↑
原分支提交重新应用
基本用法
Bash
# 将当前分支变基到 main
git checkout feature
git rebase main
# 变基到指定提交
git rebase <commit>
rebase 流程
Bash
# 1. 切换到功能分支
git checkout feature
# 2. 变基到 main
git rebase main
# 3. 处理冲突(如果有)
# 编辑冲突文件
git add <file>
git rebase --continue
# 4. 回到 main 合入
git checkout main
git merge feature # 快进合并
rebase 示例
Bash
$ git checkout feature
$ git rebase main
First, rewinding head to replay your work on top of it...
Applying: 添加功能A
Applying: 添加功能B
Successfully rebased and updated refs/heads/feature.
处理冲突
Bash
# 冲突时
$ git rebase main
CONFLICT (content): conflict in file.go
# 解决冲突
# 1. 编辑冲突文件
# 2. git add file.go
# 继续 rebase
git rebase --continue
# 跳过当前提交
git rebase --skip
# 放弃 rebase
git rebase --abort
交互式 rebase
text
# 交互式编辑提交
git rebase -i <commit>
# 交互式修改最近3次提交
git rebase -i HEAD~3
# 编辑器显示
pick a1b2c3 提交A
pick d4e5f6 提交B
pick g7h8i9 提交C
# 可改为
pick a1b2c3 提交A
squash d4e5f6 提交B # 合并到上一个
edit g7h8i9 提交C # 编辑此提交
交互式选项
| 命令 | 说明 |
|---|---|
| pick | 保留提交 |
| reword | 修改提交信息 |
| edit | 编辑提交 |
| squash | 合并到上一个提交 |
| drop | 删除提交 |
rebase 注意事项
重要规则:不要对已推送到远程的分支执行 rebase!
原因:
- rebase 改写历史,产生新提交
- 远程已有旧提交,会造成冲突
- 团队成员基于旧提交工作会受影响
要点总结
- rebase 使历史线性化
git rebase <branch>变基到指定分支-i交互式编辑提交历史- 冲突时用 --continue/--skip/--abort
- 不要对已推送的分支执行 rebase
📝 发现内容有误?点击此处直接编辑