Skip to content

Instantly share code, notes, and snippets.

@sposmen
Last active October 31, 2018 19:42
Show Gist options
  • Save sposmen/061bb4eb2aa40b024bcef90c0be238ba to your computer and use it in GitHub Desktop.
Save sposmen/061bb4eb2aa40b024bcef90c0be238ba to your computer and use it in GitHub Desktop.
Git clone only an specific directory

Usage

git_clone_only_dir -g <GIT_REPO> -d [-s <CLONE_DIR>] [-h] -- clone a specific git repository directory

where:
-g git repository
-d directory to clone
-s directory to place the clone (default will be a random one)
-h show this help text

#!/usr/bin/env bash
usage="$(basename "$0") -g <GIT_REPO> -d <DIRECTORY> [-s <CLONE_DIR>] [-h] -- clone a specific git repository directory
where:
-g git repository
-d directory to clone
-s directory to place the clone (default will be a random one)
-h show this help text
"
sflag=false
gflag=false
dflag=false
while getopts ':g:d:s:h' option; do
case "$option" in
h) echo "$usage"
exit
;;
g) GIT_REPO=$OPTARG
gflag=true
;;
d) DIRECTORY=$OPTARG
dflag=true
;;
s) CLONE_DIR=$OPTARG
sflag=true
;;
:) printf "missing argument for -%s\n" "$OPTARG" >&2; echo "$usage" >&2; exit 1;;
\?) printf "illegal option: -%s\n" "$OPTARG" >&2; echo "$usage" >&2; exit 1;;
*) echo "Unimplemented option: -$OPTARG" >&2; echo "$usage" >&2; exit 1;;
esac
done
shift $((OPTIND - 1))
if ! $gflag
then
printf "missing argument -g\n" >&2; echo "$usage" >&2; exit 1;
fi
if ! $dflag
then
printf "missing argument -d\n" >&2; echo "$usage" >&2; exit 1;
fi
if $sflag
then
mkdir -p $CLONE_DIR
else
CLONE_DIR=$(mktemp -d XXXXXXXXX)
fi
cd $CLONE_DIR && \
git init && \
git config core.sparsecheckout true && \
echo $DIRECTORY >> .git/info/sparse-checkout && \
git remote add -f origin $GIT_REPO && \
git pull origin master && \
echo "Directory $DIRECTORY is now clonned
To check it call:
cd $CLONE_DIR/$DIRECTORY && ls
"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment