使用 Git branch

共同開發一個專案必須會使用branch相關的指令,包括git branch, git checkout, 以及 git merge
文章內容將走過以下流程: 1. 創立多個feature branch 2. 切換到名為”feature2”的branch 3. 將編修過後的”feature2” 接回到master branch。

git branch

  • 用途1:查看branch
    1
    2
    3
    # * denote the current working branch
    $ git branch
    * master
  • 用途2:創立branch (1. 創立多個feature branch)
    1
    2
    3
    $ git branch feature1 #創立名為"feature1"的branch
    $ git branch feature2 #創立名為"feature2"的branch
    $ git branch feature3 #創立名為"feature3"的branch
  • 用途3:刪除branch
    1
    2
    3
    4
    5
    6
    $ git branch -d feature3 #刪除名為"feature3"的branch
    Deleted branch feature3 (was 1d9e1c2).
    $ git branch #查看刪除"feature3"後的狀態
    feature1
    feature2
    * master

git checkout

  • 用途:切換branch(2. 切換到名為”feature2”的branch)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    $ git branch #查看切換branch前的狀態
    feature1
    feature2
    * master
    $ git checkout feature2 #切換
    Switched to branch 'feature2'
    $ git branch #查看切換branch後的狀態
    feature1
    * feature2
    master
    在git graph 上,空心的節點用以表示編輯中的位置,可以看到feature2在切換過後被以空心的節點表示。

git merge

  • 用途:合併branch (3. 將編修過後的”feature2” 接回到master branch)
    首先,先將工作的branch切換到master:

    1
    2
    $ git checkout master
    Switched to branch 'master'

    在git graph 上,空心的節點換到了master branch上:

    1
    $ git merge feature2

  • Note: 最左邊的branch不一定是master。

關於將branch同步到github的題外話

  • Push並不會將所有的git branch 部屬到 github :
    1
    2
    3
    4
    $ git branch
    feature1
    * master
    $ git push
    在master的branch上做push後,github的結果如下:

    若是希望將名為”feature1”這個branch部屬到github,我們需要先checkout到”feature1”並執行以下的指令:
    1
    2
    3
    $ git checkout feature1 
    Switched to branch 'feature1'
    $ git push --set-upstream origin feature1
    執行後github的結果如下: