As a developer, you can create as many branches as possible from a single repository. Then, once the changes in a single branch are complete and ready to be introduced to the main project, you can merge them.
The illustration below depicts how git branching works.
If you clone a git repository, git will only download the main branch and not others. Therefore, if you need to work on features that are located in other branches, you will need to download and switch the repository to those branches manually.
This tutorial will learn how to download and clone other branches from a git repository.
Git Clone Remote Branches – Method 1
To clone a branch in a git repository, start by cloning the master repository using the git clone command.
For this tutorial, we will use the Golang repository:
Once complete, navigate into the repo directory.
The next step is to locate the target branch on which you wish to work. You can accomplish this by using the git branch command
The command will show the branches that are available in the local repository. To view even the remote branches, use the -a flag.
In this case, the command will show the hidden branches available in the remote repository.
Suppose you want to work on the remote branch ‘dev.tls’? First, we need to clone the branch to our local repository and tell git to switch to that branch.
We can do this by running the git checkout command followed by the name of the branch we wish to use.
An example command is as shown:
You can verify that the branch you wish to use is available using the git branch command:
* dev.tls
master
From the output above, we can see we have access to the dev.tls and master branches.
Git Clone All Branches – Method 2
In some cases, you may target a specific branch from a repository. Instead of cloning the master branch, you can specify only the required branch using the -b option in the git clone.
For example:
In the command above, we tell git to fetch the dev.tls branch from the specified repository URL.
We can then check the available branches as follows:
* dev.tls
You can see that we only have the target branch.
Conclusion
This article guides you on two main techniques of cloning specific branches from a git repository.