A Detailed Guide to Checking Out and Switching Branches in Git

Checkout is a versatile and important command in Git that allows you to switch branches, restore files, and checkout specific commits. Git 2.23 introduced the clearer git switch and git restore commands to share the responsibilities of checkout.

1. Overview of the checkout Command

(1) The Multiple Functions of "checkout"

git checkout is a multifunctional command:

100%
graph TB
    A[git checkout] --> B[Switch Branches]
    A --> C[Create a Branch]
    A --> D[Restore Files]
    A --> E[Checkout and Submit]
    
    style A fill:#fff3cd
    style B fill:#d4edda
    style C fill:#c3e6cb
    style D fill:#cce5ff
    style E fill:#f8d7da

(2) Introduction of New Commands

Because there were too many checkout functions, Git 2.23 introduced two new commands:

(3) Command Comparison

Operation checkout switch/restore
Switch Branch git checkout <branch> git switch <branch>
Create and Switch git checkout -b <branch> git switch -c <branch>
Restore File git checkout -- <file> git restore <file>
Restore Stash git checkout HEAD -- <file> git restore --staged <file>

2. Switch Branches

(1) Basic Switching

▶ Example: Switching to an existing branch

BASH
# Traditional Method
git checkout feature

# A New Approach(Recommendations)
git switch feature

# Output:
# Switched to branch 'feature'

# Switch tomainBranch
git switch main

# Output:
# Switched to branch 'main'
# Your branch is up to date with 'origin/main'.

(2) Detailed Explanation of the Switching Process

When switching branches, Git performs the following actions:

100%
sequenceDiagram
    participant User
    participant Git
    participant HEAD
    participant Workspace
    
    User->>Git: git switch feature
    Git->>Git: Check unsaved changes
    Git->>HEAD: UpdateHEADPointer
    HEAD->>Git: OrientationfeatureBranch
    Git->>Workspace: Update File
    Workspace->>User: Switchover complete

(3) Switch Options

▶ Example: Using the toggle option

BASH
# Switch to the previous branch
git switch -

# Output:
# Switched to branch 'main'

# Switch Branches and Create a Branch(If it does not exist)
git switch -c new-feature

# Force Switch(Discard Local Changes)
git switch -f feature

# Switch workspaces without changing them(Update OnlyHEAD)
git switch --detach feature

3. Creating and Switching Branches

(1) Create a new branch

▶ Example: Create and Switch Immediately

BASH
# Traditional Method
git checkout -b feature

# A New Approach(Recommendations)
git switch -c feature

# Output:
# Switched to a new branch 'feature'

# Created based on a specific commit
git switch -c feature a1b2c3d

# Created from a remote branch
git switch -c feature origin/feature

# Output:
# Branch 'feature' set up to track remote branch 'feature' from 'origin'.
# Switched to a new branch 'feature'

(2) Options for creating a branch

▶ Example: Options for Creating a Branch

BASH
# Create a branch but do not switch to it
git branch feature

# Create and Switch,Set Up an Upstream Branch
git switch -c feature --track origin/feature

# Create a branch based on a specific tag
git switch -c v1.1-branch v1.0.0

# Create from a commit on another branch
git switch -c feature main~5

4. Detected Files

(1) Restoring Files from the Repository

▶ Example: Restoring Workspace Files

BASH
# Traditional Method
git checkout -- README.md

# A New Approach(Recommendations)
git restore README.md

# Restore from a Specific Commit
git restore --source=a1b2c3d README.md

# Restore from HEAD (Latest Commit)
git restore --source=HEAD README.md

# Restore Multiple Files
git restore file1.js file2.js

# Restore the entire directory
git restore src/

(2) Restoring from the staging area

▶ Example: Unstaging

BASH
# Traditional Method
git reset HEAD README.md

# A New Approach(Recommendations)
git restore --staged README.md

# Cancel the temporary save and restore the workspace at the same time
git restore --staged --worktree README.md

# Or
git checkout HEAD -- README.md

(3) Recover Deleted Files

▶ Example: Recovering Accidentally Deleted Files

BASH
# Accidentally Deleted Files
rm important-file.js

# Restore from the repository
git restore important-file.js

# Or
git checkout HEAD -- important-file.js

# View Deleted Files
git status

# Output:
# deleted:    important-file.js

# Recover All Deleted Files
git restore .

5. Checkout and Commit (Separate Head Pointer)

(1) What is a decoupling pointer?

When a commit—rather than a branch—is checked out, HEAD points directly to that commit instead of to a branch pointer. This state is called "Detached HEAD."

100%
graph TB
    subgraph Normal State
        HEAD1[HEAD] --> main1[main]
        main1 --> C1[SubmitC3]
    end
    
    subgraph Separator Arrow
        HEAD2[HEAD] --> C2[Submita1b2c3d]
        main2[main] --> C2
    end
    
    style HEAD1 fill:#d4edda
    style HEAD2 fill:#f8d7da

(2) Enter the separation head pointer state

▶ Example: Checking out a specific commit

BASH
# Detect Specific Commits
git checkout a1b2c3d

# Output:
# Note: switching to 'a1b2c3d'.
# 
# You are in 'detached HEAD' state. You can look around, make experimental
# changes and commit them, and you can discard any commits you make in this
# state without impacting any branches by switching back to a branch.
#
# HEAD is now at a1b2c3d feat: Add a login feature

# Detection Label
git checkout v1.0.0

# Detect Remote Branches
git checkout origin/feature

(3) Operating in the separator head pointer state

▶ Example: Operations under the separator pointer

BASH
# Currently in the "separate head" pointer state
git status

# Output:
# HEAD detached at a1b2c3d
# nothing to commit, working tree clean

# You can view the code
git log --oneline

# You can edit the file
echo "test" > test.js

# Can be submitted
git add test.js
git commit -m "test commit"

# Output:
# [detached HEAD d4e5f6g] test commit
#  1 file changed, 1 insertion(+)
#  create mode 100644 test.js

# ⚠️ Note:This commit is not on any branch.!

(4) Save the changes to the split-head pointer

▶ Example: Save changes to a new branch

BASH
# A commit was created while the pointer was in the split head state.

# Method1:Create a new branch and save
git switch -c new-branch

# Output:
# Switched to a new branch 'new-branch'

# Method2:Merge into the existing branch
git branch temp-branch
git switch main
git merge temp-branch
git branch -d temp-branch

# If you switch branches without saving
git switch main

# You can do this byreflogRetrieve
git reflog
# d4e5f6g HEAD@{0}: checkout: moving from a1b2c3d to main
# a1b2c3d HEAD@{1}: commit: test commit

# Create a branch pointing to that commit
git branch saved-work d4e5f6g

6. Resolving Conflicts When Switching Branches

(1) Handling Unsaved Changes

When switching branches, if there are uncommitted changes in the working directory, the following may occur:

▶ Example: Handling Unsaved Changes

BASH
# View Current Status
git status

# Output:
# Changes not staged for commit:
#   modified:   README.md

# Situation1:Modifications do not conflict with the new branch
git switch feature
# Switch Successful,The change has been saved

# Situation2:Conflicts Between Changes and a New Branch
git switch feature
# Output Error:
# error: Your local changes to the following files would be overwritten by checkout:
#   README.md
# Please commit your changes or stash them before you switch branches.

(2) Methods for Resolving Switching Conflicts

▶ Example: Resolving Switching Conflicts

BASH
# Methods1:Submit Changes
git add .
git commit -m "WIP: Save as Draft"
git switch feature

# Methods2:Save Changes Temporarily(stash)
git stash
git switch feature
# After completing other tasks
git switch main
git stash pop

# Methods3:Cancel Edits
git restore .
git switch feature

# Methods4:Force Switch(Discard Changes)
git switch -f feature

# Methods5:Carry, Modify, Toggle(If possible)
git switch -m feature
# GitI'll try to merge the changes.

7. checkout vs switch vs restore

(1) Summary of Command Comparisons

100%
graph TB
    A[GitCommand Selection] --> B{Operation Type}
    B -->|Switch Branches| C[git switch]
    B -->|Restore Files| D[git restore]
    B -->|Complex Operations| E[git checkout]
    
    style C fill:#d4edda
    style D fill:#c3e6cb
    style E fill:#fff3cd

▶ Example: Using Modern Git Commands

BASH
# Switch Branches - Usageswitch
git switch feature
git switch -c new-feature

# Restore Files - Usagerestore
git restore README.md
git restore --staged README.md

# Detect Specific Commits - Usageswitch --detach
git switch --detach a1b2c3d

# checkoutReserved for special cases
git checkout HEAD~5 -- file.js  # Restore a Specific File from a Previous Version

❓ FAQ

Q Which one should I use: checkout, switch, or restore?
A We recommend using the new commands: git switch to switch branches and git restore to restore files. git checkout is too complex and can be confusing. However, checkout is still useful in certain advanced scenarios.
Q What is a split-head pointer? What are the risks?
A A "detached head" refers to a situation where HEAD points directly to a commit rather than a branch. The risk is that commits in this state do not belong to any branch and may be lost when switching branches. It is recommended to create a new branch to save your work.
Q What should I do if I get a prompt about unsaved changes when switching branches?
A There are three options: 1) Commit the changes before switching; 2) Use git stash to stage the changes; 3) Use git restore . to discard the changes. Choose the appropriate method based on the importance of the changes.
Q How do I restore a file from a previous version?
A Use git restore --source=<commit> <file> or git checkout <commit> -- <file> to restore files from a specified commit. For example: git restore --source=HEAD~5 README.md.
Q How do I save my work while the cursor is in the split mode?
A Use git switch -c <new-branch> to create a new branch and save your current work. If you’ve already switched branches, you can use git reflog to retrieve the commit, and then use git branch <name> <commit> to create the branch.

📖 Summary


📝 Exercises

  1. Basic Exercise: Create multiple branches, use git switch to switch between them, observe how the workspace changes when switching branches, and understand the role of the HEAD pointer.

  2. Advanced Exercise: Simulate a "head-pointing" scenario: Check out a specific historical commit, create a commit in that state, and then use git switch -c to create a new branch to save your work.

  3. Challenge: Simulate a real-world development scenario: While developing a feature on a feature branch, you suddenly need to switch to the main branch to fix an urgent bug. Use stash to save your current work, and after fixing the bug, restore your work and continue development.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏