I always forget the exact syntax to do shallow clones in git. I recently tracked it down for a few different use cases, so I thought I'd document them in one place since the documentation is kind of diffuse.

Shallow-clone a remote branch. §

$ git clone --branch $BRANCH_NAME --depth=1 $GIT_URL

Shallow-clone a remote tag. §

$ git clone --branch $TAG_NAME --depth=1 $GIT_URL

Not a typo, --branch works with tags too.

Shallow-clone a particular commit. §

This one gets a little hairy, because --branch doesn't work with commit hashes.

$ git init my_repo; cd my_repo
$ git remote add origin $GIT_URL
$ git fetch --depth=1 origin $COMMIT_HASH
$ git checkout $COMMIT_HASH

There are two big downsides to doing it this way:

  1. It doesn't fetch tags. If you add -t / --tags it will download all tags, and all objects that are pointed to by any tag (which can be a lot of data).

    You can view remote tags with

    $ git ls-remote --tags origin

    but I haven't found a way to download only the tags that are attached to that commit, or download the remote tags without pulling in every linked object.

  2. It's the exact opposite of ergonomic.

If anyone knows of a simpler way to do this, please let me know!

Comments? Get in touch on twitter: @codeandbitters