當倉庫龐大(數 GB 歷史)、頻寬受限、或僅需特定分支部署時,完整 git clone 既浪費時間又佔用空間。Git 提供多種單分支檢出策略,本文對比各方案優劣,並給出生產環境最佳實踐。

| 方案 | 適用場景 | 優點 | 缺點 |
|---|---|---|---|
--single-branch | 僅需單分支最新代碼 | 語法簡單,官方支援 | 仍下載該分支完整歷史 |
--depth=1 淺層克隆 | CI/CD、快速部署 | 極小體積,極快速度 | 無完整歷史,無法推送 |
| 稀疏檢出 | 大型單倉庫僅需子目錄 | 只下載所需文件 | 配置較繁瑣 |
| 裸倉庫 + 手動檢出 | 已有工作目錄、遷移場景 | 可覆蓋現有文件 | 步驟較多 |
git clone --branch <分支名> --single-branch <倉庫URL> [目標目錄]
# 示例
git clone --branch release/v1.2 --single-branch https://github.com/user/repo.git ./deploy
注意: 目標目錄必須為空,否則報錯 fatal: destination path '.' already exists。
# 僅獲取最新提交,體積最小
git clone --branch main --depth=1 https://github.com/user/repo.git
# 需要標籤時
git clone --branch v2.0 --depth=1 --tags https://github.com/user/repo.git
git clone --filter=blob:none --sparse https://github.com/user/repo.git
cd repo
git sparse-checkout set frontend/src backend/api # 僅檢出指定目錄
cd /existing/deploy/path
git init
git remote add -f origin https://github.com/user/repo.git
git config core.sparseCheckout true
echo "dist/*" > .git/info/sparse-checkout
git pull origin main --allow-unrelated-histories # 強制合併無關歷史
# .gitlab-ci.yml / GitHub Actions 片段
variables:
GIT_DEPTH: 1 # 淺層克隆
GIT_STRATEGY: fetch # 僅獲取變更
deploy_job:
script:
- git clone --branch $CI_COMMIT_REF_NAME --depth=1 $CI_REPOSITORY_URL .
- ./build-and-deploy.sh
git fetch --unshallow 恢復完整歷史--single-branch 後需切換分支:git fetch origin <新分支> && git checkout <新分支>--recurse-submodules --depth=1--tags 或後續 git fetch --tags單分支檢出不是單一命令,而是根據「體積敏感度、歷史需求、寫入權限、目錄結構」四個維度選型:部署用 --depth=1、開發用 --single-branch、Monorepo 用稀疏檢出、遷移用裸倉庫初始化。掌握組合拳,讓 Git 操作從「等待下載」變為「即時可用」。
Linux 系統死機安全重啟:Magic SysRq Key 完整操作指南
RHEL/CentOS 7 使用 nmcli 管理網路連線完整教學
CentOS 6.5 安裝 OpenCV 2.3.1 完整實戰:依賴套件、cmake 編譯、環境配置、測試驗證
Linux userdel 指令完整指南:刪除使用者帳號與家目錄的最佳實踐
Ubuntu 桌面版啟用藍牙耳機完整設定 (A2DP 高保真模式)
Linux 系統安裝 Apache OpenOffice 完整指南:從卸載 LibreOffice 到中文環境配置
Linux fstab 遺失導致無法開機?急救模式重建完整步驟
Arch Linux/Manjaro 掛載 iPhone 完整教學:安裝 libimobiledevice 與 ifuse 步驟