【Git】rebase 用法小結
本文主要參考
rebase在git中是一個非常有魅力的命令,使用得當會極大提高自己的工作效率;相反,如果亂用,會給團隊中其他人帶來麻煩。它的作用簡要概括為:可以對某一段線性提交歷史進行編輯、刪除、複製、貼上;因此,合理使用rebase命令可以使我們的提交歷史乾淨、簡潔!
前提:不要通過rebase對任何已經提交到公共倉庫中的commit進行修改(你自己一個人玩的分支除外)
1.合併多個commit為一個完整commit
當我們在本地倉庫中提交了多次,在我們把本地提交push到公共倉庫中之前,為了讓提交記錄更簡潔明瞭,我們希望把如下分支B、C、D三個提交記錄合併為一個完整的提交,然後再push到公共倉庫。
現在我們在測試分支上新增了四次提交,我們的目標是把最後三個提交合併為一個提交:

這裡我們使用命令:
git rebase -i [startpoint] [endpoint]
其中-i
的意思是--interactive
,即彈出互動式的介面讓使用者編輯完成合並操作,[startpoint]
[endpoint]
則指定了一個編輯區間,如果不指定[endpoint]
,則該區間的終點預設是當前分支HEAD
所指向的commit
(注:該區間指定的是一個前開後閉的區間)。
在檢視到了log日誌後,我們執行以下命令:
git rebase -i 36224db
或:
git rebase -i HEAD~3
然後我們會看到如下介面:

上面未被註釋的部分列出的是我們本次rebase操作包含的所有提交,下面註釋部分是git為我們提供的命令說明。每一個commit id 前面的
pick
表示指令型別,git 為我們提供了以下幾個命令:
根據我們的需求,我們將commit內容編輯如下:
- pick:保留該commit(縮寫:p)
- reword:保留該commit,但我需要修改該commit的註釋(縮寫:r)
- edit:保留該commit, 但我要停下來修改該提交(不僅僅修改註釋)(縮寫:e)
- squash:將該commit和前一個commit合併(縮寫:s)
- fixup:將該commit和前一個commit合併,但我不要保留該提交的註釋資訊(縮寫:f)
- exec:執行shell命令(縮寫:x)
- drop:我要丟棄該commit(縮寫:d)

然後是註釋修改介面:


2.將某一段commit貼上到另一個分支上
當我們專案中存在多個分支,有時候我們需要將某一個分支中的一段提交同時應用到其他分支中,就像下圖:

我們希望將develop分支中的C~E部分複製到master分支中,這時我們就可以通過rebase命令來實現(如果只是複製某一兩個提交到其他分支,建議使用更簡單的命令:
git cherry-pick
)。在實際模擬中,我們建立了master和develop兩個分支:
master分支:


git rebase [startpoint] [endpoint] --onto [branchName]
其中,[startpoint]
[endpoint]
仍然和上一個命令一樣指定了一個編輯區間(前開後閉),--onto
的意思是要將該指定的提交複製到哪個分支上。
所以,在找到C(90bc0045b)和E(5de0da9f2)的提交id後,我們執行以下命令:
git rebase 90bc0045b^ 5de0da9f2 --onto master
注:因為[startpoint]
[endpoint]
指定的是一個前開後閉的區間,為了讓這個區間包含C提交,我們將區間起始點向後退了一步。
執行完成後檢視當前分支的日誌:



所以,雖然此時HEAD所指向的內容正是我們所需要的,但是master分支是沒有任何變化的,
git
只是將C~E部分的提交內容複製一份貼上到了master所指向的提交後面,我們需要做的就是將master所指向的提交id設定為當前HEAD所指向的提交id就可以了,即:
git checkout master
git reset --hard 0c72e64

此時我們才大功告成!
注:文中如有任何錯誤,請各位批評指正!
相關文章
- git rebase --onto 的奇妙用法Git
- [Git]rebaseGit
- git rebaseGit
- Git -- RebaseGit
- git rebase 和 git mergeGit
- Git——rebase命令Git
- git rebase -iGit
- git rebase 流程Git
- git rebase masterGitAST
- git學習之git rebaseGit
- 如何理解git rebase?Git
- git rebase的使用Git
- [Git] Git整理(四) git rebase 的使用Git
- Git rebase 與 Git merge 的使用Git
- Git基礎命令之git rebase命令Git
- 學會使用 git-rebaseGit
- git-rebase進階使用Git
- 撤銷rebase與git原理Git
- 徹底搞懂 Git-RebaseGit
- webpack用法小結Web
- git rebase(變基)—— Git 學習筆記 19Git筆記
- 詳解git rebase,讓你走上git大神之路Git
- Git使用小結Git
- Git教程十九:分支管理之RebaseGit
- git merge和rebase的區別Git
- 你根本不懂rebase-使用rebase打造可讀的git graphGit
- git rebase後出現(master|REBASE 1/10)的解決辦法GitAST
- git:rebase(變基)的使用和理解Git
- 對git的rebase(變基)的理解Git
- Git中merge和rebase的區別Git
- git rebase沖掉記錄找回方法Git
- git分支管理--rebase&merge詳解Git
- git 爬坑小結Git
- git在工作中正確的使用方式----git rebase篇Git
- 面試官:主說 Git Rebase 和 Git Merge 差異面試Git
- Git應用詳解第九講:Git cherry-pick與Git rebaseGit
- 圖解 Git 基本命令 merge 和 rebase圖解Git
- git學習小總結Git
- git 子模組使用小結Git