How to clone a specific branch in Git?

207
git clone from branch

Git is a distributed version control system designed to track changes to a project (code) in software development. It is intended to enforce coordination, collaboration, speed, and efficiency among developers. git clone is a Git command-line utility that is used to target an existing repository and create a clone, or copy of the target repository. In this article, we will learn how to clone from a specific branch from the remote repository.

At first, let’s look at how to clone from the git repository. This is pretty straightforward. For demo purposes, we will use GitHub. We can run the git clone command with repository link. I will clone using SSH key but you may clone using HTTPS link as well.

git clone https://github.com/vijayrana99/startup.git

This will clone all the branches from the remote repository. To test, you can run the command git branch -a command. This will list all the available branches. We can simply test by switching to a branch with the command git checkout branchname.

So, how do we clone from the specific branch? Well, this is quite simple. We just need to branch name along with the URL. We can run the below command to clone the repository from a branch, let’s say staging branch.

#Syntax
git clone -b <branch> <remote_repo>

#example
git clone -b staging <remote_url>

If we run the command to list all the branches as mentioned above, git branch -a it will list all branches but default to the branch one that we cloned from. However, if we want to clone ONLY the single branch, we can run the following command. With Git 1.7.10 and later, add --single-branch to prevent fetching of all branches. Example, with staging branch:

git clone -b staging --single-branch <remote_url>
Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.