DEV Community

Cover image for How to clone a subdirectory of a git project (not downloading the zip).
darker
darker

Posted on • Updated on

How to clone a subdirectory of a git project (not downloading the zip).

Have you ever wonder a way to clone a specific folder in a git repository ?

hop hop hop, easy.. he was not talking about Downloading a ZIP(like DownGit does), but only cloning a sub-dir, just to make things clear !

I got that question from a friend, and i wrote a small and interesting bash script to do so :

#!/bin/bash

# First parameter is the sub-directory-absolute-path
# Second parameter is the link of the repo

# A smart split to get the repo-name, with / as a separator
REPO_NAME="$(echo $2 | grep -oE '[^/]+$')"

git init $REPO_NAME
cd $REPO_NAME

git remote add origin $2
git config core.sparsecheckout true

# Specipy the sub directory
echo "$1/*" >> .git/info/sparse-checkout
# then get it, the depth is the way too far wher you can go...
git pull origin master

# and badaboum, you only get your sub-dir
# this script is functionnal for github/gitlab and bitbucket
Enter fullscreen mode Exit fullscreen mode

You just have to save this bash file and pass parameters to it, for example :

$ sh sub_clone.sh app https://github.com/sanix-darker/random-repo
Enter fullscreen mode Exit fullscreen mode

Source Code : Gist-Code

Have FUN !

Discussion (0)