304 North Cardinal St.
Dorchester Center, MA 02124
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.
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.
git clone -b <branch> <remote_repo>
git clone -b gh-pages email@example.com:singhkshitij/My-Landing-Page.git
Here we are cloning branch
gh-pages from repo
But this will also clone other branches of the repository.
[su_label type=”success”]Suggested read : [/su_label] Best NoSQL databases list
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.
git clone --single-branch -b <branch> <remote_repo>
git clone --single-branch -b gh-pages firstname.lastname@example.org: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
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.
git clone --branch <branch> --depth <depth> <repository>
git clone --single-branch -b gh-pages --depth 10 email@example.com:singhkshitij/My-Landing-Page.git
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.