在 git clone 时指定分支,最直接的方式是用 -b 参数。但根据需求深浅,有几种不同的用法:
一、最常用:克隆时直接检出指定分支
git clone -b <分支名> <仓库地址>
示例:
git clone -b develop https://github.com/user/repo.git
效果:
• 拉取完整仓库(包含所有分支的元数据)
• 克隆完成后,工作区直接停在 develop 分支上(等价于 clone 完再执行 git checkout develop)
💡 -b 后面不仅可以跟分支名,还可以跟 tag 名或 commit hash:
git clone -b v1.2.0 https://github.com/user/repo.git # 按 tag 检出
git clone -b a1b2c3d https://github.com/user/repo.git # 按 commit 检出(Git 2.0+)
二、进阶:只克隆指定分支(不拉其他分支的历史)
上面的方式虽然检出了指定分支,但 Git 仍然会把所有分支的完整历史都下载下来。如果你只想拉某一个分支、节省时间和带宽:
git clone -b <分支名> --single-branch <仓库地址>
示例:
git clone -b develop --single-branch https://github.com/user/repo.git
效果对比:
方式 下载内容 本地分支 适用场景
默认 git clone 所有分支的完整历史 只有 main/master 常规开发
-b develop 所有分支的完整历史 直接检出 develop 想直接在某分支上开始工作
-b develop --single-branch 只有 develop 分支的历史 只有 develop 大仓库、CI 构建、只需单个分支
⚠️ 用了 --single-branch 后,本地 git branch -a 看不到其他远程分支。如果后续需要其他分支:
# 允许跟踪所有远程分支
git remote set-branches origin '*'
# 再拉取
git fetch origin
三、极限优化:浅克隆 + 单分支(CI/CD 最常用)
如果你只需要最新代码、不需要历史提交记录(比如 CI 构建、Docker 部署):
git clone -b <分支名> --single-branch --depth 1 <仓库地址>
示例:
git clone -b main --single-branch --depth 1 https://github.com/user/repo.git
参数 作用
-b main 指定分支
–single-branch 只拉这个分支
–depth 1 只拉最近 1 次提交,历史截断
效果:下载量可能从几百 MB 降到几 KB~几 MB,速度极快。
💡 后续如果想拉取完整历史:
git fetch --unshallow # 拉取完整历史
四、完整参数速查
最基础:clone 完直接切到 develop 分支
git clone -b develop https://github.com/user/repo.git
只拉 develop 分支、不要其他分支
git clone -b develop --single-branch https://github.com/user/repo.git
只要 develop 分支的最新一次提交(极速、极小)
git clone -b develop --single-branch --depth 1 https://github.com/user/repo.git
指定目录名(不想要默认的 repo 文件夹名)
git clone -b develop https://github.com/user/repo.git my-folder
五、常见坑
问题 原因 解决
-b 指定的分支不存在 远程没有这个分支名 检查拼写,或先不指定 -b,clone 完 git branch -a 看看有哪些分支
clone 后 git branch 只看到当前分支 用了 --single-branch 正常行为,需要 git remote set-branches origin ‘*’ && git fetch
想拉 tag 但提示 “not a branch” -b 跟 tag 时某些旧版 Git 行为不同 升级 Git 到 2.0+,或 clone 完再 git checkout
总结
你的需求 用这条命令
克隆后直接在某分支上工作 git clone -b <分支>
大仓库,只要一个分支的历史 git clone -b <分支> --single-branch
CI/部署,越快越小越好 git clone -b <分支> --single-branch --depth 1

4879

被折叠的 条评论
为什么被折叠?



