全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-11 8 分钟 ✍️ juanwangdev

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 改写历史,产生新提交
  • 远程已有旧提交,会造成冲突
  • 团队成员基于旧提交工作会受影响

要点总结

  1. rebase 使历史线性化
  2. git rebase <branch> 变基到指定分支
  3. -i 交互式编辑提交历史
  4. 冲突时用 --continue/--skip/--abort
  5. 不要对已推送的分支执行 rebase

📝 发现内容有误?点击此处直接编辑

← 上一篇 git merge --no-ff 禁用快进
下一篇 → rebase vs merge 选择
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库