06 - 分支管理(Branch)

05-Push與Pull | 下一篇 → 07-常見問題與解法


🌿 什麼是分支(Branch)?

分支讓你可以在不影響主線的情況下,嘗試新功能或修改內容。

main ────●────●────●────●─────
              ↑         ↑
           分支點      合併點
              └────●────●─ (feature branch)

使用情境

  • 想試試看一個新的寫法,怕改壞主要內容
  • 多人協作,每個人在自己的分支工作,完成後再合併
  • 同時進行多個不同的功能開發

🔍 查看分支

# 查看所有本地分支(* 表示目前所在的分支)
git branch
 
# 查看所有分支(包含遠端)
git branch -a

➕ 建立新分支

# 建立分支(但不切換過去)
git branch feature/new-notes
 
# 建立分支並立即切換過去(推薦)
git switch -c feature/new-notes
 
# 舊版寫法(一樣可以用)
git checkout -b feature/new-notes

分支命名建議:

  • feature/xxx — 新功能
  • fix/xxx — 修正問題
  • docs/xxx — 文件修改

🔀 切換分支

# 切換到指定分支
git switch main
 
# 舊版寫法
git checkout main
 
# 切換到上一個分支
git switch -

🔗 合併分支(git merge)

當分支上的工作完成了,把它合併回主分支:

# 先切換回 main
git switch main
 
# 將 feature 分支合併進來
git merge feature/new-notes

Fast-forward merge vs. Merge commit

# 強制建立 merge commit(有清楚紀錄)
git merge --no-ff feature/new-notes

🗑️ 刪除分支

# 刪除已合併的分支(安全)
git branch -d feature/new-notes
 
# 強制刪除(即使還沒合併)
git branch -D feature/new-notes
 
# 刪除遠端分支
git push origin --delete feature/new-notes

🌍 Push 分支到 GitHub

# 把本地分支推到 GitHub
git push -u origin feature/new-notes

🔄 Rebase(進階)

rebase 是另一種整合分支的方式,讓歷史更整潔。

# 在 feature 分支上,把 main 的最新內容接進來
git switch feature/new-notes
git rebase main

merge vs rebase

  • merge 保留完整歷史,多一個 merge commit
  • rebase 讓歷史線性,看起來更乾淨
  • 初學者先用 merge 就好

📌 小結

指令用途
git branch查看分支
git switch -c 分支名建立並切換新分支
git switch 分支名切換分支
git merge 分支名合併分支
git branch -d 分支名刪除分支
git push -u origin 分支名Push 分支到 GitHub

05-Push與Pull | 下一篇 → 07-常見問題與解法