跳到主要内容

从 Git 仓库中克隆特定文件夹

· 阅读需 2 分钟
wen

Clone a Specific Folder from a Git Repository

You can use sparse checkout in Git to download only a specific folder from a repository. Here's how:

Steps

  1. Create a Folder and Navigate to It:

    mkdir <folder-name>
    cd <folder-name>
  2. Initialize Git:

    git init
  3. Add the Repository URL:

    git remote add origin <repo-url>
  4. Enable Sparse Checkout:

    git sparse-checkout init
  5. Select the Folder to Clone:

    git sparse-checkout set <folder-path>

    Replace <folder-path> with the folder you want (e.g., docs).

  6. Download the Folder:

    git pull origin <branch>

    Replace <branch> with the branch name (e.g., main).

Example

To download only the docs folder:

mkdir my-repo
cd my-repo
git init
git remote add origin https://github.com/example/repo.git
git sparse-checkout init
git sparse-checkout set docs
git pull origin main

Key Points

  • Git Version: Sparse checkout requires Git 2.25 or later.
  • Multiple Folders: Add multiple folders by separating them with spaces:
git sparse-checkout set folder1 folder2
  • Disable Sparse Checkout: If you want to clone the whole repo later:
git sparse-checkout disable

This method saves time and space by downloading only the files you need!

Loading Comments...