How to clone a branch in git with just 2 commands

If you are wondering how to clone a branch in git, while using GitHub or GitLab, the article explains a couple of ways to do so in the fastest way possible.

We will be using git clone command. These are all the flags command offers.

 git clone [--template=<template_directory>]
[-l] [-s] [--no-hardlinks] [-q] [-n] [--bare] [--mirror]
[-o <name>] [-b <name>] [-u <upload-pack>] [--reference <repository>]
[--dissociate] [--separate-git-dir <git dir>]
[--depth <depth>] [--[no-]single-branch] [--no-tags]
[--recurse-submodules[=<pathspec>]] [--[no-]shallow-submodules]
[--jobs <n>] [--] <repository> [<directory>]

To see which flag does what, please run below command, it describes each of them briefly.

git help clone

So we have two methods to clone a repo. Let’s see all of them in action.

1. Fetch all branches but checkout one

When you want to check out one branch but alongside other branch changes also need to be fetched or cloned.

If no branch will be specified, command clones master or main branch.

Command:

git clone -b <branch> <remote_repo>

Example :

git clone -b gh-pages [email protected]:singhkshitij/My-Landing-Page.git

Here we are cloning branch gh-pages from repo https://github.com/singhkshitij/My-Landing-Page .

But this will also clone other branches of the repository.

[su_label type=”success”]Suggested read : [/su_label] Best NoSQL databases list

2. Fetch and checkout one branch

When you want to check out only one branch but do not want to clone others.

You can pass --single-branch flag to git clone command and it will prevent other branches to be cloned while cloning the desired branch.

Command:

git clone --single-branch -b <branch> <remote_repo>

Example :

git clone --single-branch -b gh-pages [email protected]:singhkshitij/My-Landing-Page.git

Here we are cloning just one branch gh-pages from repo.

[su_label type=”success”]Suggested read : [/su_label] 11 Best Editor for Web Development IDEs

3. Clone limited commits

If you want to limit the number of commits to be cloned, using --depth the flag to specify the number of commits you want to clone.

Command :

git clone --branch <branch> --depth <depth> <repository>

Example :

git clone --single-branch -b gh-pages --depth 10 [email protected]:singhkshitij/My-Landing-Page.git

4. Other useful git clone flags

  • git branch -a: List all branches in local.
  • --shallow-since=<date> : Will clone only commits from history after the specified date.
  • --shallow-exclude=<revision> : Will exclude specific commit while cloning the repo. This is really helpful if you have made a bad commit on top.
  • <directory> : If you want to clone to seperate directory than the default git directory. This comes handy when you want to clone some project and create your own copy of it.

Let us know if that helped you. If you know some other way how to clone a branch in git, please let us know.

Leave a Comment