How to Clone a Single Branch in Git

Sometimes it is necessary to clone a single and specific git branch. The classic git clone command with the option of --branch will clone the overall Git Repository and check out the particular branch, followed by the --branch.

When your purpose is just to clone a very particular branch, you need to run another command. In the 1.7.10 Git version and above, to solve the purpose, you need to invoke:

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

The option of --single-branch selects the particular branch.

In the older Git versions for cloning a specific branch are used the git init, git remote and git checkout commands, like this:

git init
git remote add -t <branchname> -f origin <remote-repo-url>
git checkout <branchname>

How to Clone Repository and Check Out to a Specific Branch

It is possible to clone the whole repository and checkout to a specific branch using a single command. To meet this goal, you need to use the git clone command like this:

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

It is better not to run this command in case you wish to work with a single branch having nothing to do with the rest of the branches. On the contrary, using this command is a perfect idea, if you want to check out a specific branch now and to switch to the rest of the branches later.

The Usage of Git Branch

Git branches should be an important part of your daily working process.

The branching feature is available in most of the version control systems. It is used to create, delete or list branches. Branches act as an isolated development line. They represent a way of requesting a new working directory, project history, and staging area. When you develop isolated development lines for 2 features, it will allow working on them on parallel making the master branch free of uncertain codes.

Definition of the git init Command

This command is aimed at creating a new, not filled repository or reinitializing an existing Git repository. Using this command you create a .git subdirectory. The subdirectory includes metadata.

Git init is a super-easy way of creating version-controlled projects. You just need to cd into the subdirectory of your project, then run the git init command. In this way, you’ll have a fully functional Git repository.

Defining Git Remote

This command is used to create, view and remove connections to other Git repositories. The connections of Git remote are bookmarks in other repositories. They represent convenient naming used for referencing a not-so-convenient URL.

Definition of Git Checkout

You can use this command for switching branches or restoring working tree files. It can be run on branches, commits, and files. It works along with the git branch command. Git checkout is aimed at updating files in the working directory to match the version which is stored in the branch. It tells Git to record all the new commits.

Do you find this helpful?

Related articles