创建新的 Git 分支有多种方法,下面是详细的命令和说明。

基本命令

1. 创建并切换到新分支(最常用)

git checkout -b <新分支名>

或者使用更直观的新命令(Git 2.23+):

git switch -c <新分支名>

示例:

git checkout -b feature/user-authentication
# 或
git switch -c feature/user-authentication

2. 仅创建分支(不切换)

git branch <新分支名>

示例:

git branch feature/user-authentication

基于特定基准创建分支

1. 基于当前分支创建

git checkout -b <新分支名>

2. 基于其他分支创建

git checkout -b <新分支名> <基准分支名>

示例:

# 基于main分支创建新功能分支
git checkout -b feature/new-feature main

# 基于develop分支创建修复分支
git checkout -b hotfix/urgent-fix develop

3. 基于特定提交创建

git checkout -b <新分支名> <提交哈希>

示例:

# 基于特定提交创建分支
git checkout -b experiment a1b2c3d

4. 基于远程分支创建本地分支

git checkout -b <本地分支名> origin/<远程分支名>

示例:

# 基于远程的feature/login分支创建本地分支
git checkout -b feature/login origin/feature/login

完整工作流程示例

场景 1:开发新功能

# 1. 确保在主分支并更新到最新
git checkout main
git pull origin main

# 2. 创建并切换到新功能分支
git checkout -b feature/user-profile

# 3. 开始开发,进行一些提交
git add .
git commit -m "Implement user profile basic structure"

# 4. 将新分支推送到远程(可选)
git push -u origin feature/user-profile

场景 2:修复紧急bug

# 1. 从主分支创建热修复分支
git checkout main
git checkout -b hotfix/critical-bug

# 2. 修复bug并提交
git add .
git commit -m "Fix critical security issue"

# 3. 推送到远程
git push -u origin hotfix/critical-bug

分支命名最佳实践

使用有意义的命名约定:

# 功能分支
feature/user-authentication
feature/payment-integration

# 修复分支
hotfix/urgent-security-patch
bugfix/login-error

# 发布分支
release/v1.2.0

# 实验性分支
experiment/new-algorithm

实用技巧

1. 查看分支创建情况

# 查看所有分支(星号表示当前分支)
git branch -a

# 查看分支的最后提交
git branch -v

# 查看已合并/未合并的分支
git branch --merged
git branch --no-merged

2. 推送到远程仓库

创建分支后,通常需要推送到远程:

# 推送并设置上游跟踪分支
git push -u origin <分支名>

# 后续推送可以简写为
git push

3. 删除刚创建的分支(如果需要)

# 切换回主分支
git checkout main

# 删除本地分支
git branch -d <分支名>

完整示例演示

# 开始新功能开发
$ git status
On branch main
Your branch is up to date with 'origin/main'.

# 创建并切换到新分支
$ git checkout -b feature/notification-system
Switched to a new branch 'feature/notification-system'

# 确认当前分支
$ git branch
  main
* feature/notification-system

# 进行一些开发工作...
$ echo "新功能代码" > notification.py
$ git add notification.py
$ git commit -m "Add notification system base"

# 推送到远程
$ git push -u origin feature/notification-system

使用新的 git switch 命令(推荐)

Git 2.23 版本引入了更清晰的命令:

# 创建并切换到新分支
git switch -c feature/new-feature

# 切换到已存在的分支
git switch main

# 切换到之前的分支(类似 cd -)
git switch -

总结

场景 命令 说明
创建并切换 git checkout -b <分支名> 最常用的方式
仅创建 git branch <分支名> 创建但不切换
基于其他分支 git checkout -b <新分支> <基准分支> 基于指定分支创建
推送到远程 git push -u origin <分支名> 首次推送设置上游

最佳实践建议:

  1. 创建分支前先更新主分支:git pull origin main
  2. 使用有意义的命名约定
  3. 及时推送到远程备份
  4. 定期合并主分支的更新到功能分支

记住:分支是 Git 的强大功能,不要害怕创建分支!频繁创建和合并分支是 Git 工作流的正常部分。