How to Clone a Specific Git Branch Directly from the Command Line

Git Tips
How to Clone a Specific Git Branch Directly from the Command Line

When working on collaborative software projects, active development and test-ready code often live on dedicated branches—such as develop—rather than the primary main or master branch.

By default, running git clone downloads the entire repository and checks out the default branch. However, if you want to start working on develop or any other branch immediately, you can tell Git to check out your target branch as soon as the cloning process finishes.


1. The Standard Command: Clone and Check Out a Specific Branch

To clone a repository and automatically switch to a specific branch in a single step, use the -b (or --branch) flag:

git clone -b <branch-name> <repository-url>

Practical Example

If you want to clone the develop branch of a repository:

git clone -b develop https://github.com/pepito/my-project.git

Once execution completes, Git will have downloaded the project and automatically set develop as your active working branch.


2. Performance Optimization: Clone a Single Branch Only (--single-branch)

By default, the previous command fetches the history for all remote branches in the repository, even though it checks out develop.

If the repository is large or you only need to work on that specific branch without pulling the rest of the commit history, add the --single-branch flag. This speeds up the process and reduces disk usage:

git clone -b develop --single-branch https://github.com/pepito/my-project.git

Note: With --single-branch, your local clone will only track the specified branch. If you need to access other remote branches later, you will need to update your remote fetch configuration.


3. Verifying Your Active Branch

After cloning, navigate into the project directory and verify which branch is active:

cd my-project
git branch

You will see an asterisk * next to develop, confirming that your local environment is ready for development.

Comments