Git 中没有独立的 checkout -b 命令,实际为 git checkout -b(创建并切换分支),而 Git 2.23+ 推荐用 git switch -c 替代,两者均支持基于指定提交或远程分支创建,且需注意分支名不可省略、未提交更改会阻止切换等关键细节。

Git 中没有 checkout -b 这个独立命令,但你很可能指的是 git checkout -b —— 这是 Git 早期版本中创建并切换分支的常用方式。不过从 Git 2.23(2019年)起,官方推荐使用更语义清晰的 git switch 和 git restore 替代部分 git checkout 功能。下面分两种情况说明:
用 git checkout -b 创建并切换新分支(兼容旧版本)
这是最直接的方式,适用于所有 Git 版本(包括最新版):
-
语法:
git checkout -b <branch-name></branch-name> - 它等价于先运行
git branch <branch-name></branch-name>,再运行git checkout <branch-name></branch-name> - 可选:基于指定提交或远程分支创建,例如:
git checkout -b feature/login origin/main或git checkout -b hotfix-123 abc7890
用 git switch 创建并切换新分支(Git 2.23+ 推荐)
如果你使用的是较新 Git(建议升级),git switch 更专注“切换分支”这一目的,语义更明确:
-
创建并切换:
git switch -c <branch-name></branch-name>(-c即--create) - 同样支持基于其他起点创建:
git switch -c dev --track origin/develop(自动设置上游跟踪) - 若只想创建不切换,用
git switch -C <branch-name></branch-name>(大写 C,强制创建并重置已有分支)
常见误区提醒
避免混淆这些易错点:
-
git checkout <branch-name></branch-name>(无-b)仅切换,不创建;如果分支不存在会报错 -
git checkout -b后面必须跟分支名,不能省略;否则会尝试把当前暂存区检出为文件,可能误删工作区内容 - 在有未提交更改时执行
git switch或git checkout,Git 默认会阻止切换(除非加-f强制),这是保护机制
小技巧:一步完成开发流程
日常开发中,常需要从 main 拉出新功能分支并立即开始工作:
git checkout main && git pull && git checkout -b feat/user-profile- 或更简洁(Git 2.23+):
git switch main && git pull && git switch -c feat/user-profile - 想让新分支自动跟踪远程对应分支?加上
--track或简写-t:git switch -c feat/api -t origin/feat/api


















