How to download a single folder or directory from a GitHub repo
Overview
Sometimes, we are only interested in a single folder from a repository. When we download a single folder, it allows us to work fast and not have to carry the baggage that sometimes comes with downloading the entire repository.
For example, a UI engineer might only want the UI folder from the entire micro-service repo.
Code example
We’ll use one of the public repos for this example. Here is the link to it.
mkdir Codingcd Coding/git initgit remote add origin -f https://github.com/anjanashankar9/Coding.gitvim .git/info/sparse-checkout# Add leetcode to the filegit config core.sparseCheckout truegit pull origin masterls
Code explanation
- Line 1: We create an empty directory on our machine.
- Line 3: We go into that directory and initialize Git in this directory.
- Line 4: We add the remote.
- Lines 5 and 6: We have the sparse-checkout functionality. The files/folders that we like to checkout should be added to
.git/info/sparse-checkout.
Note: In the
vim, pressito open the file and writeleetcodeto edit it. To exit thevim, press escape and type:xto save and exit the file.
Once we set the config to sparse-checkout, we can do a pull.
Run the above commands in the terminal below:
We can think of the sparse-checkout file as the reverse of the .gitignore file.
This is an extremely handy trick for large repos, especially when we only have to work with a small number of files or folders from it.