Skip to content

git rebase 使用#

git rebase 的主要作用是将一个分支的多个提交合并到一块 并提交到另一个分支上 (PR),它的设计目的是为了创建更线性、整洁的提交历史。

典型工作流#

# 1. 在 feature 分支上压缩提交
git checkout feature

# 2. 交互式 rebase 压缩当前分支 最近 N 个提交
git rebase -i HEAD~3  # 3 是要压缩的提交数量

# 在编辑器中,将第一个提交设为 "pick",后续提交设为 "squash" 或 "s"
# 保存退出后会提示编辑新的提交信息

# 3. 切换回 master 更新并合并
git checkout master
git pull origin master 
git merge feature

# 4. 解决冲突 ,测试通过后再 push
git push origin master

git rebase 交互命令#

输入指令 git rebase -i HEAD~3 后,会出现以下交互编译窗口:

p 45eba1b 2.6
s d57c52f dev 2.6.1
s 6ffb751 dev 2.6.2

# Rebase 8632d1f..c095e36 onto 8632d1f (3 commands)
#
# 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 [-C | -c] <commit> = like "squash" but keep only the previous
#                    commit's log message, unless -C is used, in which case
#                    keep only this commit's message; -c is same as -C but
#                    opens the editor
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# 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>]
# .       create a merge commit using the original merge commit's
# .       message (or the oneline, if no original merge commit was
# .       specified); use -c <commit> to reword the commit message
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.

示意图#

gitGraph
    commit id: "main-init"
    branch feature-1
    branch feature-2
    checkout feature-1
    commit id: "1.1" 
    commit id: "1.2" 
    commit id: "1.3"

    checkout feature-2 
    commit id: "2.1" 
    commit id: "2.2" 


    checkout feature-1
    commit tag: "rebase 1.1~1.3" type: HIGHLIGHT

    checkout main
    merge feature-1

    checkout feature-2
    merge main 
    commit tag: "rebase 2.1~2.2" type: HIGHLIGHT

    checkout main
    merge feature-2

注意事项#

  1. 不要对已推送的公共分支执行 rebase
    这会重写提交历史,导致与他人分支冲突,如果需要 rebase 已推送分支,需确保团队允许并通知所有协作者。

  2. 本地分支操作前先备份
    使用 git checkout -b backup-branch 创建备份分支,防止 rebase 出错后丢失工作进度。

  3. 处理冲突时谨慎操作
    rebase 过程中遇到冲突需逐步解决,每步完成后用 git rebase --continue,中断可用 git rebase --abort 完全退出。

  4. 避免对合并提交直接 rebase
    默认 rebase 会丢弃合并提交,需添加 -p--rebase-merges 保留合并结构,但可能增加复杂性。

  5. 远程分支需强制推送更新(不建议使用)
    若 rebase 了已推送的本地分支,推送时需用 git push -f,但需确保无他人基于旧提交开发。

  6. 测试 rebase 结果
    完成后运行代码测试,确保功能正常,再进行推送。