Pulling a single sub-folder from a remote git repo

Posted by Trond Aarskog on March 06, 2015

While doing some work on my home automation system I found a library on github that could be useful. The problem was that the code I needed was located in a sub-folder and I didn't want to "pollute" my structure with all the other files.

I found a rather old but related question on Stackoverflow with the perfect solution from Daniel Schroeder. There is another answer with more votes, but that one uses -f as the argument which downloads everything to the .git-folder. I only want this single folder on my machine - not the complete repo.

The steps:

$ git init <repo>
$ cd <repo>
$ git remote add origin <url>
$ git config core.sparsecheckout true
$ echo "<SUB-FOLDER_YOU_WANT>/*" >> .git/info/sparse-checkout
$ git pull

If you need to - you can of course add more folders to the "sparse-checkout" file.

Update 2021: Revisiting the Q on Stackoverflow indicates git now have even better support...