如何把 Git 仓库克隆到指定目录
克隆到指定目录:git clone <仓库地址> <目录名>;克隆到当前目录(已存在的空目录)用 git clone <地址> .(注意句点)。目标目录必须不存在或为空。
在 clone 命令末尾加目录名即可:git clone <仓库地址> my-folder,仓库内容会进 my-folder 而不是默认的仓库名目录。想直接克隆进当前所在的空目录,用句点:git clone <仓库地址> .
用法
git clone https://github.com/org/repo.git my-folder # 指定目录名
git clone https://github.com/org/repo.git . # 克隆进当前空目录
git clone https://github.com/org/repo.git /opt/apps/api # 绝对路径
约束
- 目标目录不存在 → Git 会创建它;
- 目标目录存在但为空 → 允许;
- 目标目录非空 → 报错
destination path already exists and is not an empty directory。
非空目录想硬克隆进去?换个思路:
git init .
git remote add origin <仓库地址>
git fetch
git checkout -t origin/main
常用组合选项
git clone --depth 1 <地址> dir # 浅克隆,只要最新快照
git clone -b develop <地址> dir # 克隆指定分支
git clone --recursive <地址> dir # 连子模块一起
常见问题(FAQ)
Q:克隆错了目录怎么补救?
克隆出的仓库是自包含的(含 .git),直接 mv my-folder correct-folder 移动即可,git 操作不受影响。
Q:同一仓库能克隆到多个目录吗?
可以,各自独立工作互不干扰(worktree 是更省磁盘的替代:git worktree add ../dir2 分支)。
Q:克隆进当前目录提示非空但我要保留现有文件?
用上面的 init+fetch 方案。注意若现有文件与仓库内容同名不同内容,checkout 会冲突,需先处理。