Git is a distributed version control system that allows you to keep a central remote repository and maintain local copies of the repository on every developer’s system. Generally, developers clone the complete repository to their local system before they start working with it. Sometimes you may have a very large repository and you may need to work only with a few subfolders in it and not the complete repository. In such cases, you may need to clone subdirectory of git repository. In this article, we will learn how to clone subdirectory of git repository.
How to Clone Subdirectory of Git Repository
Here are the steps to clone subdirectory of git repository. Please note, they are applicable for git >=1.7.0.
1. Create Empty Repository
If you already have a remote repository, you can skip this step. Otherwise, open terminal and run the following commands to create a push a new empty repository. Replace <url> with the URL of your remote repository.
$ mkdir <repo> $ cd <repo> $ git init $ git remote add -f origin <url>
2. Do a Sparse Checkout
The above command will create an empty remote repository but not checkout the objects in it. You can do so by setting the following value in your local git repository.
$ git config core.sparseCheckout true
Next, you need to include the folders and subfolders that you want to clone in .git/info/sparse-checkout file. You can do so by running the following commands. Replace /path/to/dir with the folder path
$ echo "path/to/dir/" >> .git/info/sparse-checkout
3. Push to Master
Lastly, you need to push the changes to remote master with the following command.
$ git pull origin master
Please note, these steps will still download the entire repository but only reduce the size of checkout.
Since git 2.25.0 there is a new experimental feature of sparse-checkout. Here are some sample commands using sparse-checkout.
git sparse-checkout init # git config core.sparseCheckout true git sparse-checkout set "/path/to/folder" # echo "/path/to/folder" >> .git/info/sparse-checkout git sparse-checkout list # cat .git/info/sparse-checkout
In this article, we have learnt how to clone subdirectory of git repository.
How to Get Remote URL of Local Git Repository
How to Remove File from Git Repository
How to Get One File from Another Branch in Git
How to Change Git Commit Message
How to Force Git Pull to Overwrite Local Files