git switch 和git checkout 区别

Core Differences

git checkout is the older command with many functions; git switch is the newer command designed specifically for switching branches, offering clearer semantics.

You can understand it this way:

Command Primary Purpose Characteristics
git checkout Switch branches, restore files, check out commits Feature-rich, prone to confusion
git switch Switch branches only Clearer, recommended for beginners

1. Switching to an Existing Branch

Legacy syntax:

git checkout dev

Modern syntax:

git switch dev

Both achieve the same result: switching to the dev branch.


2. Creating and Switching to a New Branch

Legacy syntax:

git checkout -b feature-login

Modern syntax:

git switch -c feature-login

This means: create the feature-login branch and switch to it.


3. Differences When Restoring Files

git checkout can also restore files—for example:

git checkout -- app.js

This discards local modifications to app.js and restores it to the version in the repository.

However, git switch cannot restore files—it handles branches exclusively.

To restore files, Git now recommends using:

git restore app.js

Thus, Git later split the old checkout command into two clearer, more focused commands:

Legacy Command Modern Command
git checkout <branch-name> git switch <branch-name>
git checkout -- <file-name> git restore <file-name>

4. Checking Out a Specific Historical Commit

git checkout allows direct switching to a specific commit:

git checkout 77171b4

This puts you in a detached HEAD state.

git switch, by default, focuses on branch operations. To switch to a specific commit, you must be more explicit:

git switch --detach 77171b4

Recommended Usage

For everyday development, use:

git switch <branch-name>

To create and switch to a new branch:

git switch -c <new-branch-name>

To discard modifications to a file:

git restore <file-name>

To view a historical version:

git switch --detach <commit-id>