基本分支切换

1. 切换到已存在的本地分支

git checkout <branch-name>
# 或使用较新的命令
git switch <branch-name>

示例:

git checkout develop
git switch feature/login

2. 创建并切换到新分支

git checkout -b <new-branch-name>

git switch -c <new-branch-name>

示例:

git checkout -b feature/search
git switch -c hotfix/bug-123

高级分支操作

3. 切换到远程分支

# 先获取远程分支信息
git fetch origin

# 切换到远程分支(会自动创建本地跟踪分支)
git checkout --track origin/<remote-branch>
# 或简写
git checkout <remote-branch>

示例:

git fetch origin
git checkout --track origin/feature/payment

4. 基于特定提交创建分支

git checkout -b <new-branch> <commit-hash>

示例:

git checkout -b test-branch a1b2c3d

5. 切换到标签

git checkout tags/<tag-name>

示例:

git checkout tags/v1.0.0

分支切换时的注意事项

6. 处理工作目录变更

有未提交的更改:

# 暂存更改
git stash
# 切换分支
git checkout other-branch
# 恢复更改
git stash pop

丢弃本地更改:

git checkout -- .          # 丢弃所有未暂存修改
git clean -fd             # 删除未跟踪的文件和目录
git checkout <branch>     # 然后切换分支

7. 查看分支信息

git branch       # 查看本地分支
git branch -a    # 查看所有分支(包括远程)
git branch -v    # 查看分支最后提交信息

常见问题解决

8. 错误:“Your local changes would be overwritten”

解决方法:

# 选项1:提交更改
git commit -am "Save changes before switching"

# 选项2:暂存更改
git stash
git checkout other-branch
# 之后可以 git stash pop 恢复

# 选项3:丢弃更改(谨慎使用)
git reset --hard
git checkout other-branch

9. 错误:“pathspec ‘branch-name’ did not match any file(s)”

可能原因:

  • 分支不存在

  • 未获取远程分支

解决方法:

git fetch origin
git checkout -b local-branch origin/remote-branch
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐