How to Clone a Single Branch in Git

  1. Cloning a single branch using git remote add
    1. Creating a new repository
    2. Adding the remote and fetching the branch
  2. Cloning a single branch using git clone
  3. The git branch Command
  4. The git init Command
  5. The git remote Command
  6. The git checkout Command

Sometimes it is necessary to clone a single and specific git branch. Let’s take a look at different approaches and take the steps to get the job done!

Cloning a single branch using git remote add

1. Creating a new repository

The first step should be creating a new repository with git init:

git init

2. Adding the remote and fetching the branch

The second step is to git add a remote named origin for the given repository and git fetch the given branch from origin:

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

Cloning a single branch using git clone

The classic git clone command with the option of --single-branch the branch specified by the --branch flag is cloned. If no branch is specified, the option will clone the master branch:

git clone --single-branch --branch <branchname> <remote-repo-url>
The option of --single-branch selects the particular branch.

The git branch Command

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.

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.

The git remote Command

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.

The git checkout Command

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