Git

Git Clone All Branches

In git, a branch refers to a repository version that slightly diverges from the main project. A branch allows developers to implement experimental features without affecting the main repository.

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:

$ git clone https://github.com/golang/go.git

Once complete, navigate into the repo directory.

$ cd go

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

$ git branch

The command will show the branches that are available in the local repository. To view even the remote branches, use the -a flag.

$ git branch -a

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:

$ git checkout dev.tls

You can verify that the branch you wish to use is available using the git branch command:

$ git branch

* 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:

git clone -b dev.tls https://github.com/golang/go.git

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:

$ git branch

* 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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list