git rebase 合并多个commit

git rebase命令在另一个分支基础之上重新应用,用于把一个分支的修改合并到当前分支。

使用语法

1
2
3
4
5
git rebase [-i | --interactive] [options] [--exec <cmd>] [--onto <newbase>]
    [<upstream> [<branch>]]
git rebase [-i | --interactive] [options] [--exec <cmd>] [--onto <newbase>]
    --root [<branch>]
git rebase --continue | --skip | --abort | --quit | --edit-todo

合并分支

创建一个新分支

git checkout -b feature master
git merge master

合并多个commit

使用merge合并commit

git checkout feature
git merge master

或者

git merge master feature

使用merge相对rebase要安全简单,但是每次merge都会在feature分支产生一个merge commit, 如果master更新频繁,merge次数多时会让feature分支的commit history很难看。 这时候就可以考虑使用rebase合并commits。

在feature分支上合并master分支上新的commits

git checkout feature
git rebase master

解决冲突(resolve conflicts),添加解决冲突修改内容,然后提交更新这些内容。

git add
git rebase --continue

如果出现问题或者想放弃合并执行abort终止rebase操作

git rebase --abort

这样就不会有多余的merge commit,但是也会合并其它多个commit,导致丢失commit。 这时可以选择更加灵活的rebase合并,进入rebase编辑界面,有选择的合并指定commit。

选择commit合并

查看commit id,--oneline表示一行一条commit显示

git log --oneline

选择一个commit id执行rebase合并,合并不包括选择的commit

git rebase -i [commit_id]

或者选择最近几个commit

git rebase -i HEAD~[number_of_commits]

执行rebase进入编辑界面,编辑界面操作详解

# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit

参考