How to clone a branch in Git

In this Answer, we are going to discuss how to clone a branch in Git.

Prerequisites

Reasons to clone a branch in Git

Sometimes when collaborating with other developers on a remote repository, we might need information specific to a branch alone, or we might want to clone the information on a branch that is assigned to us.

The clone command will clone the branch and the remote head, in other words, it will clone the main or master branch and other branches in the repository.

There are two methods to clone a branch:

  1. Fetch all the branches

  2. Fetch the specific branch

Fetch all the branches

Use the following code to clone a branch.

Code

git clone --branch <branchname> <remote-repo-url>

Terminal 1
Terminal
Loading...

Explanation

  • <branchname>: This specifies the name of the branch to be cloned.

  • <remote-repo-url>: This specifies the URL to the repository to be cloned.

Note: We can use -b as the alias of —-branch.

The code above configures the terminal for git push and git pull, checks out automatically to the given branch, and downloads all branches from the remote repository. However, this might not be what we want.

Note: Clicking on the terminal widget will open a connection to the terminal, where we can clone a repository from the specified URL.

Fetch the specific branch

Use the following code to clone a branch.

Code

git clone --branch <branchname> --single-branch <remote-repo-url>

Terminal 1
Terminal
Loading...

Explanation

The —-single-branch option allows us to clone files from the specified branch.

Note: This option was introduced in Git 1.7.0 and later versions.

By using the command above and substituting valid values for <branchname> and <remote-repo-url> , we would be able to clone a branch in Git seamlessly. We can try out the examples in the terminal widget above.

Free Resources