News Stay informed about the latest enterprise technology news and product updates.

How to git clone a specific branch only

When the git clone command runs, by default the master branch is checked out, and remote references to all of the other branches in the repository are copied locally as well. But that’s not 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.

git-clone@branch:~$ git status
On branch develop

git-clone@branch:~$ git branch –all
* develop
remotes/origin/HEAD -> origin/master

git clone a specific branch example

To accomplish of git cloning 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 .ist any other remote references:

git-clone@branch:~$ git branch –all
* develop

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

git-clone@branch:~$ 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 checkout 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.


Start the conversation

Send me notifications when other members comment.

Please create a username to comment.