How to git clone a specific branch only

When the git clone command runs, the master branch is checked out by default and remote references to all of the other branches in the repository are copied locally as well. But, this isn’t always what a Git user wants. Git’s “git clone branch” command can alter this behavior.

The other scenario in which the “git clone branch” command is needed is when only a single, specific git branch should be checked out. Sometimes a Git repository is massive, and not every single branch is needed. It’s not a recommended option for average, everyday users, but if you want to only git clone a specific branch, you can use the –single-branch option.

git clone a single branch

The two most common ways to use “git clone branch” are:

  1. To check out a specific branch after the git clone.
  2. To only git clone a specific branch and no others.

To accomplish the first git clone branch objective, issue the following command:

git clone --branch development

After this command was issued in the git clone branch example, a git status call indicated that development was indeed checked out, and a “git branch –all” command indicated that all remote references were cloned as well.

[email protected]:~$ git status
On branch develop

[email protected]:~$ git branch –all
* develop
remotes/origin/HEAD -> origin/master

git clone a specific branch example

To git clone only a specific branch, we issued this command:

git clone --single-branch --branch development

In contrast to the previous example, when get did the git clone of a specific branch, the branch listing did not list any other remote references:

[email protected]:~$ git branch –all
* develop

Furthermore, any attempt to check out a branch other than the specifically cloned git branch triggered an error:

[email protected]:~$ git checkout master
error: pathspec ‘master’ did not match any file(s) known to git

git clone specific branch

When you git clone a specific branch only, you cannot check out other branches.

Git clone depth for continuous delivery

It is a common requirement of a continuous integration build to only git clone a single, specific branch. After all, if all you’re doing is compiling the latest code commit in the develop branch, why clone every other branch in the process? If this is the case, you might also want to limit the git clone depth. If you set the clone depth to 1, you’ll only get the latest commit, not the entire history of the project. It’s a nice feature that might save your Jenkins server some clock-cycles, not to mention hard drive space.


App Architecture
Software Quality
Cloud Computing