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
-
Create a Folder and Navigate to It:
mkdir <folder-name>
cd <folder-name> -
Initialize Git:
git init
-
Add the Repository URL:
git remote add origin <repo-url>
-
Enable Sparse Checkout:
git sparse-checkout init
-
Select the Folder to Clone:
git sparse-checkout set <folder-path>
Replace
<folder-path>
with the folder you want (e.g.,docs
). -
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