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