How to Clone a Specific Git Branch

Kevin Amayi Feb 02, 2024
  1. Clone a Specific Git Branch From a Remote Repository by Fetching the All Branches and Checking Out to a Specific Branch
  2. Clone a Specific Git Branch Directly From a Remote Repository
How to Clone a Specific Git Branch

This article will discuss cloning a specific git branch from a remote repository by fetching all branches and checking out a specific branch.

Clone a Specific Git Branch From a Remote Repository by Fetching the All Branches and Checking Out to a Specific Branch

We will clone a remote repository containing two branches, namely master and gh-pages, and then switch to the gh-pages branch.

<!-- The command to use is -->
git clone <remote-repo-url>

<!-- From your terminal run -->
git clone https://github.com/KEVINAMAYI/AkanNameGenerator.git

Output:

Cloning into 'AkanNameGenerator'...
remote: Enumerating objects: 94, done.
remote: Total 94 (delta 0), reused 0 (delta 0), pack-reused 94
Unpacking objects: 100% (94/94), 2.38 MiB | 1.86 MiB/s, done.

We will get into the project folder and list the available branches using the commands below.

<!-- get into project folder -->
cd AkanNameGenerator

<!-- List branches available -->
git branch -a

Output:

<!-- The asterix indicates we are on branch main -->
* main
remotes/origin/HEAD -> origin/main
remotes/origin/gh-pages
remotes/origin/main

We will switch to the specific branch gh-pages using the command below.

git checkout gh-pages

We will confirm that we are in a specific branch gh-pages by running:

git branch

Output:

<!-- The asterix indicates we are now on branch gh-pages -->
* gh-pages
main

Clone a Specific Git Branch Directly From a Remote Repository

We will clone the specific branch we need directly from the remote repository by specifying the branch name in the Git command.

<!-- The command to use is -->
git clone --branch <branchname> --single-branch <remote-repo-url>

<!-- From your terminal run -->
git clone --branch gh-pages --single-branch https://github.com/KEVINAMAYI/AkanNameGenerator.git

Output:

Cloning into 'AkanNameGenerator'...
remote: Enumerating objects: 94, done.
remote: Total 94 (delta 0), reused 0 (delta 0), pack-reused 94
Unpacking objects: 100% (94/94), 2.38 MiB | 231.00 KiB/s, done.

We will get into the project folder and list the available branches by running the following.

<!-- get into project folder -->
cd AkanNameGenerator

<!-- List branches available -->
git branch -a

Output:

<!-- we have only our specific branch -->
* gh-pages

Related Article - Git Branch