git clone 命令:
该命令是把远端仓库或分支克隆到本地,基本用法如下:
git clone <仓库地址> [本地目录]
<仓库地址>:要克隆的 Git 仓库地址,可以是 HTTPS、SSH 或本地路径。
[本地目录]:克隆后存放代码的目录名称。省略,则默认使用仓库名称。
常用的参数:
1)--branch <branch-name>
/ -b <branch-name>
:
作用: 指定克隆后立即检出的特定分支或标签,而不是仓库的默认分支(通常是
main
或master
)。示例:
git clone --branch develop https://github.com/username/repo.git # 克隆并直接切换到 develop 分支
git clone -b v2.1.0 https://github.com/username/repo.git # 克隆并直接切换到标签 v2.1.0 (此时处于 'detached HEAD' 状态)
2)--depth <depth>
/ --single-branch
:
作用: 进行浅克隆 (Shallow Clone)
--depth <depth>
: 只克隆指定数量的最新提交历史。例如 --depth 1
只克隆最近一次提交(没 有历史记录)
--single-branch
: 通常与 --depth
一起使用,表示只克隆指定分支(通过 -b
指定)的历史,不获取其他分支或标签的信息。 进一步节省空间。
示例:
git clone --depth 1 https://github.com/username/large-repo.git # 只克隆最新提交
git clone --depth 1 --single-branch -b feature-x https://github.com/username/repo.git # 只克隆 feature-x 分支的最新提交
3)--recurse-submodules
/ --recursive
:
作用: 如果被克隆的仓库使用了 Git 子模块(Submodules),此选项会在克隆主仓库后,自动初始化并更新(克隆)其中包含的所有子模块。非常方便,避免了后续手动执行
git submodule update --init --recursive
。示例:
git clone --recurse-submodules https://github.com/username/repo-with-subs.git
4)--no-checkout
/ -n
:
作用: 克隆仓库,但不自动检出工作目录文件。你只得到了
.git
目录(包含所有对象和历史),工作目录是空的。克隆完成后,你需要手动执行git checkout <branch>
来检出文件。用途: 在某些自动化脚本或需要先配置再检出工作目录的场景下有用。
示例:
git clone -n https://github.com/username/repo.git
cd repo
git checkout main # 手动检出 main 分支