< Back

git rebase的使用

只说一下工作时经常遇到的一种场景:通常都是从一个主分支切一个分支出来开发,开发完成后提交PR。如果开发过程中进行了大量的commit,那么合并后主分支的历史上也会显示这些commit,而因为是多人开发,如果大家都这么干,主分支的历史记录就很难看了。这个时候就可以用git rebase来合并commit后再进行提交,让历史记录更好看。

做一个实验,从master分支切出一个dev分支,做两个提交

git commit -m 'fix 1'
git commit -m 'fix 2'

然后回到master,再做一个提交,并提交到线上,这个时候master就超过dev了

git commit -m 'master fix 1'
git push

回到dev,提交到线上,并创建PR,分支被合并后,主分支的历史会显示所有的commits

img

接下来再看看git rebase的情况,在dev上做两个提交

git commit -m 'fix 3'
git commit -m 'fix 4'

如果要打算进行git rebase最好是先合并主分支代码到dev后再执行

git pull origin master
git rebase -i master

会进入vi,显示如下

pick c776a25 fix 3
pick c916af8 fix 4

# Rebase 9ebea44..c916af8 onto 9ebea44 (4 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.
#
# However, if you remove everything, the rebase will be aborted.

修改上面那部分如下,然后保存退出

pick c776a25 fix 3
s c916af8 fix 4

出现如下信息

# This is a combination of 2 commits.
# This is the 1st commit message:

fix 3

# This is the commit message #2:

fix 4

# Please enter the commit message for your changes. Lines starting
...

将上面的两个commit信息删掉,写成一个,比如fixed some bugs

# This is a combination of 4 commits.
# This is the 1st commit message:

fixed some bugs

# Please enter the commit message for your changes. Lines starting

保存退出后,提交并创建PR,并合并后,主分支历史记录就只会显示一条记录了

img