Git Rebase 命令详解

420 阅读2分钟

Git Rebase 命令详解

什么是 git rebase

git rebase 是 Git 中用于整合分支的另一种方法(替代 git merge)。它的核心思想是将当前分支的提交“重新应用”到目标分支的最新提交之上,从而使提交历史呈现线性化,避免合并提交(merge commit)。


核心流程(图示)

1. Rebase 前状态:

假设有两个分支:

  • master 分支:提交 A → B → C
  • feature 分支:从 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,会:

  1. feature 的提交 DE 临时保存。
  2. feature 分支的基点从 B 更新到 master 的最新提交 C
  3. DE 重新应用到 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 解决冲突

  1. 冲突发生:在 rebase 过程中,如果某个提交与目标分支冲突,Git 会暂停并提示解决冲突。
  2. 手动解决冲突:编辑文件后标记为已解决:
    git add <冲突文件>
    git rebase --continue  # 继续 rebase
    
  3. 终止 Rebase
    git rebase --abort  # 放弃 rebase,回到原始状态
    

Rebase vs Merge

操作提交历史合并提交适用场景
git merge保留分支结构,生成合并提交公共分支(如多人协作)
git rebase线性历史,无合并提交私有分支(需整理本地提交历史)

注意事项

  1. 不要对公共分支使用 rebase:改写历史会导致协作混乱。
  2. 远程分支:本地 rebase 后需强制推送(git push -f),但需谨慎使用。
  3. 黄金法则:只对尚未共享的本地提交使用 rebase!

示例流程

  1. 初始状态:

    gitGraph
        commit id: "A"
        commit id: "B"
        branch feature
        commit id: "D"
        checkout main
        commit id: "C"
    
  2. 执行 git rebase main

    gitGraph
        commit id: "A"
        commit id: "B"
        commit id: "C"
        branch feature
        commit id: "D'"
    

通过 git rebase,你可以让代码提交历史更清晰、更易读!