跳到主內容

【Git】checkout 與 switch 比較

我來幫你整理 git switchgit checkout 的差異,並用表格讓你快速比較。


1️⃣ 歷史背景

  • git checkout 是 Git 早期就有的指令,功能很多,但語意太複雜,既可以切換分支、也可以檢出檔案,容易讓初學者混淆。

  • git switch(Git 2.23 之後加入)是為了讓「切換分支」這個動作更直觀而出現的,專注於分支切換,不負責檔案檢出。


2️⃣ 功能比較表

功能 git checkout git switch
切換到已存在分支 git checkout branch_name git switch branch_name
建立並切換到新分支 git checkout -b new_branch git switch -c new_branch
檢出特定 commit / tag git checkout commit_hash ❌ 不支援
檢出特定檔案版本 git checkout commit_hash -- file.txt ❌ 不支援
語意單純性 ❌ 功能太多易混淆 ✅ 專注於切換分支
推薦使用情境 老專案 / 習慣舊指令 新專案 / 想簡化操作

3️⃣ 使用範例

切換到現有分支

# 傳統方式
git checkout dev

# 新方式(推薦)
git switch dev

建立並切換到新分支

# 傳統方式
git checkout -b feature/login

# 新方式(推薦)
git switch -c feature/login

4️⃣ 為什麼官方推薦 git switch

  • 讓指令語意更明確,不再把「檔案檢出」和「分支切換」混在一起。

  • 搭配 git restore(處理檔案版本還原)更符合直覺:

    • git switch → 專注切換分支

    • git restore → 還原檔案內容


💡 簡單記

  • 切換分支 → 用 git switch

  • 還原檔案 → 用 git restore

  • 需要舊版本的行為 → 用 git checkout


太好了!以下是 git switchgit restore 如何取代舊指令 git checkout完整對照表,讓你更容易理解並開始使用新指令:


git checkout 對照表:對應的新指令用法

原本 git checkout 用法 對應的新指令 功能說明
git checkout <branch> git switch <branch> 切換到已存在的分支
git checkout -b <new-branch> git switch -c <new-branch> 建立並切換到新分支
git checkout <commit> ❌(建議保留 checkout 切換到某個 commit 狀態(暫不取代)
git checkout <file> git restore <file> 還原工作區中的單一檔案
git checkout -- <file> git restore <file> 同上
git checkout <commit> -- <file> git restore --source <commit> <file> 還原某個 commit 中的檔案
git checkout . git restore . 還原所有工作區的檔案
git checkout HEAD <file> git restore --source=HEAD <file> 還原最新 commit 的某個檔案
git checkout HEAD^ ❌(建議保留 checkout 切換到上一個 commit(建議保留舊指令)

 

💡 建議做法

任務 建議用法
切換分支 git switch dev
建新分支並切過去 git switch -c feature/new-ui
還原單一檔案 git restore src/App.tsx
還原某 commit 的檔案 git restore --source=abc123 file.txt
還原整個工作目錄 git restore .

🚀 Git 版本要求

  • git switchgit restore 需 Git 2.23 或以上

  • 使用 git --version 檢查目前版本