Git 切换分支的完整指南
基本分支切换
1. 切换到已存在的本地分支
git checkout <branch-name># 或使用较新的命令git switch <branch-name>
示例:
git checkout developgit switch feature/login
2. 创建并切换到新分支
git checkout -b <new-branch-name>
或
git switch -c <new-branch-name>
示例:
git checkout -b feature/searchgit switch -c hotfix/bug-123
高级分支操作
3. 切换到远程分支
# 先获取远程分支信息git fetch origin# 切换到远程分支(会自动创建本地跟踪分支)git checkout --track origin/<remote-branch># 或简写git checkout <remote-branch>
示例:
git fetch origingit 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 stashgit checkout other-branch# 之后可以 git stash pop 恢复# 选项3:丢弃更改(谨慎使用)git reset --hardgit checkout other-branch
9. 错误:“pathspec ‘branch-name’ did not match any file(s)”
可能原因:
-
分支不存在
-
未获取远程分支
解决方法:
git fetch origingit checkout -b local-branch origin/remote-branch