How to clone a specific feature branch from a Remote Git Repository

How to clone a specific feature branch from a Remote Git Repository

A few days ago I was working on something and had to clone a remote repository but I only needed the branch containing the starter files for that project so I had to make some findings and here are the solutions I was able to gather from the search.

To clone a specific branch from a remote git repo, there are two ways in which you can go about it, I will try to discuss the two what makes each approach different

First Method

This method allows you to clone the repository with all the branches contained in that repository but immediately checks out to the branch you specified, thereby making the branch your locally configured branch so when you perform actions like git push or git push this branch is where the actions are performed on by default.

To achieve this here is the snippet for that

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

or

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

where -b is just an alias for branch

However, when you do git fetch it will fetch the recent changes to all available branches on the repo, and this wasn't what I wanted so I made more findings and got to learn about the second method that actually did the job I wanted.

Second Method

The first method though cool wasn't what I really wanted, all I needed from that repo is just files in that specific branch and nothing else. Luckily for me, this feature was added to Git as of version 1.7.10 and it has been available since. This allows you to only fetch files from the specified branch without fetching other branches.

To test this here is the snippet for that

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

or

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

It is seen that the --single-branch is what makes the whole difference.

In case you find this article helpful please show some love, by liking this post and sharing it with your friends and colleagues.

I also promise to write articles about simple code snippets that can make a great deal in our day to day dev activities.

Thank you