Overview
In this quick tutorial, you will be shown how to clone a specific branch from a remote Git repository. When a branch is cloned from a remote repository the master branch is pulled by default. While for most use cases this is likely desirable, but sometimes you just want one specific branch at first.
Git allows us to specify a branch name using the -b flag when we clone from a remote repo.
Cloning a Specific Remote Branch
In the following example we are going to clone the official WordPress repository. WordPress creates a branch for every version, and if we were only interested in 5.2 release, we could pull down that branch instead of master.
git clone -b 5.2-branch https://github.com/WordPress/WordPress.git
The output of the command will be no different than if we did not specify a branch, as can be seen in the following example output.
Cloning into 'WordPress'…
remote: Enumerating objects: 82, done.
remote: Counting objects: 100% (82/82), done.
remote: Compressing objects: 100% (62/62), done.
remote: Total 297255 (delta 56), reused 43 (delta 20), pack-reused 297173
Receiving objects: 100% (297255/297255), 184.84 MiB | 1.68 MiB/s, done.
Resolving deltas: 100% (238351/238351), done.
Checking connectivity… done.
Checking out files: 100% (2156/2156), done.
The exception, of course, is that the master branch has not been pulled down with the 5.2-branch branch. We can verify this by running the git branch command.
git branch
* 5.2-branch
Clone Single Branch History Only
When we use the -b flag alone, we pull down the entire history of the repository, including details about other branches. If you only want the history of the branch you are cloning, the –single-branch flag can be used.
Using the –single-branch flag is useful in Continuous Integration (CI) pipelines, as we only care about the history of the branch that is being built. We don’t pollute our build server with unnecessarily wasted space, we is important when dealing with large projects with a long history.
git clone -b 5.2-branch --single-branch https://github.com/WordPress/WordPress.git
Let us compare the output of this command with the output above.
Cloning into 'WordPress-Single'…
remote: Enumerating objects: 55, done.
remote: Counting objects: 100% (55/55), done.
remote: Compressing objects: 100% (41/41), done.
remote: Total 269795 (delta 33), reused 29 (delta 14), pack-reused 269740
Receiving objects: 100% (269795/269795), 157.62 MiB | 1.86 MiB/s, done.
Resolving deltas: 100% (216860/216860), done.
Checking connectivity… done.
Checking out files: 34% (734/2156)
Checking out files: 35% (755/2156)
Checking out files: 100% (2156/2156), done.
Right away you should notice that the number of enumerated objects is much lower, and we can confirm this by looking at the object size difference too.
The first clone we did, without using the –single-branch flag, has an object size of 184 MiBs, while the second clone has an object size of 157 MiBs.