从远程仓库拉取分支的多种方法
技术背景
在使用Git进行项目开发时,经常需要从远程仓库拉取分支到本地进行开发。不同版本的Git以及不同的使用场景,有多种方法可以实现这一需求。
实现步骤
使用 git switch
命令(Git新版本)
如果远程仓库存在 daves_branch
分支,但本地没有该分支,可直接使用以下命令:
由于本地没有该分支,switch
会自动在远程仓库查找,并自动设置远程分支跟踪。但如果 daves_branch
本地不存在,使用 switch
前需要先执行 git fetch
。
创建跟踪远程分支的本地分支
较新版本的Git
1
| git checkout --track origin/daves_branch
|
--track
是 git checkout -b [branch] [remotename]/[branch]
的简写,这里 [remotename]
是 origin
,[branch]
是 daves_branch
。
Git 1.5.6.5
1
| git checkout --track -b daves_branch origin/daves_branch
|
Git 1.7.2.3 及更高版本
1
| git checkout daves_branch
|
不过在较新版本的Git中,此命令不会创建本地分支,而是会使你处于“分离头指针”状态。如果需要创建本地分支,使用 --track
选项。
使用 fetch
和 checkout
组合
1 2
| git fetch <remote> <rbranch>:<lbranch> git checkout <lbranch>
|
其中 <rbranch>
是远程分支,<lbranch>
是要跟踪的本地分支(该分支本地尚不存在)。如果不指定本地分支名,在 checkout
时可以使用 -b
标志创建。
简单方法
方法一
1 2
| git fetch origin branchName git checkout branchName
|
可以使用 git branch -r
查看远程分支是否存在。
方法二
1 2
| git fetch --all git checkout YourBranch
|
适用于远程存在但本地不存在的分支。
方法三
1
| git checkout -b 'YourBranch' origin/'YourRemote'
|
这可能是最简单的方法。
克隆特定远程分支
1
| git clone url --branch remote_branch_name
|
例如:
1
| git clone git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git --branch v3.15
|
核心代码
拉取并切换到远程分支
1 2
| git fetch origin git checkout --track origin/<remote_branch_name>
|
拉取所有远程分支
最佳实践
- 在拉取远程分支前,建议先使用
git branch -r
查看所有远程分支。 - 如果不确定使用哪种方法,优先考虑使用
git switch
或 git checkout --track
命令。 - 对于克隆特定远程分支的场景,使用
git clone url --branch remote_branch_name
可以避免克隆整个仓库。
常见问题
浅克隆仓库无法拉取远程分支
如果仓库是使用 --depth 1
克隆的,很多命令可能无法正常工作。例如:
1 2 3
| git clone --depth 1 https://github.com/repo/code cd code git checkout other_branch
|
可能会报错 error: pathspec 'other_branch' did not match any file(s) known to git.
。
这种情况下可以重新克隆仓库,也可以参考相关解决方案:https://stackoverflow.com/questions/23708231/git-shallow-clone-clone-depth-misses-remote-branches。