# git switch 与 git checkout 的区别

**URL:** <https://forum.beginner.center/t/topic/2933>\
**Category:** 🛠工具与编程\
**Tags:** git\
**Created:** [2026 年7 月 8 日 06:30 UTC](https://forum.beginner.center/t/topic/2933 "2026-07-08T06:30:10Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![doggie](https://forum.beginner.center/user_avatar/forum.beginner.center/doggie/32/550_2.png) [@doggie](https://forum.beginner.center/u/doggie)\
**Post date:** [2026 年7 月 8 日 06:30 UTC](https://forum.beginner.center/t/topic/2933/1 "2026-07-08T06:30:10Z")

</div>

# 核心区别

`git checkout` 是老命令，功能很多；`git switch` 是新命令，专门用于 **切换分支** ，语义更清晰。

可以这样理解：

| 命令 | 主要用途 | 特点 |
| --- | --- | --- |
| `git checkout` | 切换分支、恢复文件、检出提交 | 功能杂，容易混淆 |
| `git switch` | 只用于切换分支 | 更清晰，推荐新手使用 |

## 1. 切换已有分支

老写法：

```bash
git checkout dev

```

新写法：

```bash
git switch dev

```

作用一样：切换到 `dev` 分支。

* * *

## 2. 创建并切换新分支

老写法：

```bash
git checkout -b feature-login

```

新写法：

```bash
git switch -c feature-login

```

含义是：创建 `feature-login` 分支，并切换过去。

* * *

## 3. 恢复文件时的区别

`git checkout` 还可以用来恢复文件，比如：

```bash
git checkout -- app.js

```

意思是：丢弃 `app.js` 的本地修改，恢复到仓库里的版本。

但 `git switch` **不能恢复文件** ，它只管分支。

现在恢复文件更推荐用：

```bash
git restore app.js

```

所以 Git 后来把老的 `checkout` 拆成了两个更清晰的命令：

| 老命令 | 新命令 |
| --- | --- |
| `git checkout 分支名` | `git switch 分支名` |
| `git checkout -- 文件名` | `git restore 文件名` |

* * *

## 4. 检出某个历史提交

`git checkout` 可以直接切到某个 commit：

```bash
git checkout 77171b4

```

这会进入 detached HEAD 状态。

`git switch` 默认更偏向分支操作，如果要切到某个 commit，需要写得更明确：

```bash
git switch --detach 77171b4

```

# 推荐用法

日常开发建议：

```bash
git switch 分支名

```

创建并切换新分支：

```bash
git switch -c 新分支名

```

丢弃某个文件修改：

```bash
git restore 文件名

```

查看历史版本：

```bash
git switch --detach commit_id

```

* * *
