git 常用操作五 - git branch

介紹

每次 git commit 會產生一個提交,每個提交看作是一個節點,多個點連成一條枝幹。

git 的命令中有針對單個提交的,也有針對分支操作。(之前幾節介紹的命令都是針對單個提交)

當 git 庫中存在多條分支時,用 git log --graph ,也可以直觀的感受到分支的概念。

如果有可視話工具,如gitg,則更爲直觀:

圖中可以看到兩條分支,分支名分別是 master  和 dev_branch 。

概念

可以將分支理解爲一系列提交的集合,外加一個分支名。

分支=分支名+提交集合

常用操作

差看分支

可以通過 git branch -a 查看當前庫中的分支。

默認分支

在git 庫中做第一個提交後,git 會自動創建一個名爲 master 的分支。

創建分支

git branch branch_name 來創建新分支。例如:git  branch dev_branch

然後,再通過 git branch -a 查看,可以看到兩個分支。

這裏要說明一下 [ 當前分支 ] 的概念,圖中 master 前面帶了一個 * 號,表示當前處在 master 分支上,也意味着後續 git commit 創建的提交(節點)都是在這個分支上的。可以做兩個提交實驗一下:

先通過 git log 命令,可以觀察到,當前兩個分支上都只有一個提交,也就是git庫中唯一的一個提交:

接下來在 當前分支,也就是 master 分支上創建兩個提交:

(touch 命令創建一個文件)

再通過 git log 可以看到  master  分支上有三個提交,dev_branch 上還是隻有一個提交

也可以通過 gitg 工具進行觀察:

切換當前分支

使用 git checkout branch_name 進行切換當前分支的操作。

假設當前處於 master 分支,那麼通過 git checkout dev_branch 可以切換當前分支:

這裏需要特別說明:

之前的文章裏介紹過 git checkout [commit-id] 命令,是會將當前的 [工作區,暫存區,版本庫] 都切到特定的提交。

git checkout [branch_name] 是和 git checkout [commit-id] 完全等價的,也會將當前的 [工作區,暫存區,版本庫] 都切到分支名對應的那個的提交。

而分支名對應的提交就是分支頭(分支提交鏈條上的最後一個提交)

因此,也可以將分支名理解成一個提交的標籤(TAG),或理解成一個提交的暱稱。

 

接下來,再在 dev_branch 上做兩個新提交,這樣就得到了本文開頭的那張圖例:

參考資料

https://git-scm.com/docs/user-manual.html#what-is-a-branch

Understanding history: What is a branch?

When we need to be precise, we will use the word "branch" to mean a line of development, and "branch head" (or just "head") to mean a reference to the most recent commit on a branch. In the example above, the branch head named "A" is a pointer to one particular commit, but we refer to the line of three commits leading up to that point as all being part of "branch A".

However, when no confusion will result, we often just use the term "branch" both for branches and for branch heads.

= google translate =

瞭解歷史:什麼是分支?
當我們需要精確時,我們將使用“branch”這個詞來表示開發線,而“branch head”(或者只是“head”)則表示對分支上最近提交的引用。 在上面的示例中,名爲“A”的分支頭是指向一個特定提交的指針,但是我們引用導致該點的三個提交行,因爲它們都是“分支A”的一部分。

但是,當不會產生混淆時,我們通常只對分支和分支頭使用術語“分支”。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章