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:
- Switch Branches: Switch to a different branch
- Create and Switch Branches: Create a new branch and switch to it immediately
- Check out files: Restore files from the repository
- Detect Commit: Switch to a specific commit (split the head pointer)
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:
git switch: Specifically used for switching branchesgit restore: Specifically designed for file recovery
(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
# 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:
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
# 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
# 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
# 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
# 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
# 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
# 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."
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
# 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
# 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
# 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
# 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
# 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
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
(2) Recommended Usage
▶ Example: Using Modern Git Commands
# 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
checkout, switch, or restore?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.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.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.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.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
- The
checkoutcommand is versatile; it is recommended to useswitchandrestoreinstead. - Switch branches:
git switch <branch>Update HEAD and the working directory - Create and switch:
git switch -c <branch>—done in one step - Restore file:
git restore <file>Restore from the repository - Separate the HEAD pointer: HEAD points directly to the commit; you need to create a branch to save your work
- Handling unsaved changes: Commit, stage, or discard them before switching branches
📝 Exercises
-
Basic Exercise: Create multiple branches, use
git switchto switch between them, observe how the workspace changes when switching branches, and understand the role of the HEAD pointer. -
Advanced Exercise: Simulate a "head-pointing" scenario: Check out a specific historical commit, create a commit in that state, and then use
git switch -cto create a new branch to save your work. -
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
stashto save your current work, and after fixing the bug, restore your work and continue development.



