使用命令行拉取 Git 仓库
1. 克隆远程仓库(首次获取)
# 克隆仓库到当前目录(默认使用 HTTPS 协议)
git clone https://github.com/用户名/仓库名.git# 克隆仓库到指定目录
git clone https://github.com/用户名/仓库名.git 自定义目录名# 使用 SSH 协议克隆(需要配置 SSH 密钥)
git clone git@github.com:用户名/仓库名.git# 克隆指定分支
git clone -b 分支名 https://github.com/用户名/仓库名.git
示例:
git clone https://github.com/octocat/Spoon-Knife.git
git clone -b develop git@github.com:vuejs/vue.git my-vue-project
2. 拉取最新代码(已有本地仓库)
# 进入本地仓库目录
cd 你的仓库目录# 拉取当前分支最新代码(默认拉取 origin 远程)
git pull# 拉取指定远程的指定分支
git pull origin 分支名
3. 关联远程仓库(本地已有项目)
# 初始化本地仓库
git init# 添加远程仓库地址
git remote add origin https://github.com/用户名/仓库名.git# 验证远程仓库是否添加成功
git remote -v# 首次拉取并合并代码
git pull origin master
4. 解决常见问题
权限拒绝(Permission Denied)
# 现象:
ERROR: Repository not found.
fatal: Could not read from remote repository.# 解决方案:
1. 检查 URL 是否正确
2. 使用 SSH 协议需配置密钥:- 生成密钥:ssh-keygen -t ed25519 -C "your_email@example.com"- 将公钥(~/.ssh/id_ed25519.pub)添加到 GitHub/GitLab
3. 或切换回 HTTPS 协议
目录已存在冲突
# 现象:
fatal: destination path 'xxx' already exists and is not an empty directory.# 解决方案:
1. 删除或重命名现有目录
2. 或指定新的目录名:git clone https://github.com/xxx/xxx.git new-folder-name
5. 高级操作
稀疏克隆(只拉取部分目录)
git clone --filter=blob:none --no-checkout https://github.com/xxx/xxx.git
cd xxx
git sparse-checkout init --cone
git sparse-checkout set dir1 dir2
git checkout main
拉取子模块
# 克隆包含子模块的仓库
git clone --recurse-submodules https://github.com/xxx/xxx.git# 已有仓库初始化子模块
git submodule update --init --recursive
各协议对比
协议类型 | URL 示例 | 特点 |
---|---|---|
HTTPS | https://github.com/user/repo.git | 无需配置密钥,需输入账号密码 |
SSH | git@github.com:user/repo.git | 需配置密钥,无需每次输入密码 |
GitHub CLI | gh repo clone user/repo | 官方命令行工具,自动认证 |
常用工作流
# 完整克隆到本地
git clone https://github.com/user/repo.git
cd repo# 创建新分支
git checkout -b feature-branch# 开发完成后提交
git add .
git commit -m "完成新功能"
git push origin feature-branch