Last Updated: April 20, 2021
· barnabyalter

Checkout a single folder from a GitHub repository

Ever wanted to checkout only a single directory or file from a Git repos? Well with some footwork you can as of Git 1.9. Read the documentation for more implementation details and to understand what's going on:

But here is a quick implementation with bash.

The following will checkout one directory, errors, into a new git directory and subsequently update it (note fast-forward-only merge):



mkdir -p $DIR
if [ -d "$DIR" ]; then
  cd $DIR
  git init
  git remote add -f origin $REPOS
  git fetch --all
  git config core.sparseCheckout true
  if [ -f .git/info/sparse-checkout]; then
    rm .git/info/sparse-checkout
  echo $CHECKOUT_DIR >> .git/info/sparse-checkout
  git checkout $BRANCH
  git merge --ff-only origin/$BRANCH

2 Responses
Add your response

Thank you for this very helpful solution!

over 1 year ago ·

Thank you!
To get it working I did have to add a space on the line with

if [ -f .git/info/sparse-checkout]; then

just before the last square bracket so that it became:

if [ -f .git/info/sparse-checkout ]; then

over 1 year ago ·