How to clone a specific branch using git clone
This guide will walk you through how to clone a specific branch, explaining the necessary Git terminology and commands along the way.
Understanding git clone
git clone
is a command used to copy a Git repository, a directory or storage space where your Git projects live, from a remote location to your local machine.
This process not only downloads the files but also the entire history of changes, allowing you to work on the project locally.
Cloning a specific branch
By default, git clone
will clone the repository's default branch (typically named main
).
However, if you want to work with a different branch, a feature branch for example, you'll need to specify that branch during the clone operation.
To clone a specific branch, use the following syntax:
git clone -b <branch-name> --single-branch <repository-url>
-b <branch-name>
: This tells Git which branch you want to clone.--single-branch
: This option limits the clone to the specified branch only, omitting all other branches from the download. It's useful for saving time and space when you're interested in just one branch.
Example: cloning a feature branch
Imagine you want to clone a branch named feature-login
from a repository:
git clone -b feature-login --single-branch https://github.com/username/project.git
This command clones the feature-login
branch from the specified URL into a directory named project
on your local machine.
You'll only have the feature-login
branch available locally, not the entire repository's branches.
Cloning and checking out a branch
Sometimes, you might want to clone a repository and immediately switch to a different branch. While the -b
option effectively does this by cloning only the specified branch, here's how you'd do it manually for educational purposes or in cases where you initially cloned the entire repository:
- Clone the repository (this will clone the default branch initially):Terminalgit clone https://github.com/username/project.git
- Change directory to the cloned repository:Terminalcd project
- List all branches to find the one you want to switch to:Terminalgit branch -a
- Checkout the branch you're interested in (this will create a local branch tracking the remote branch):Terminalgit checkout -b feature-login origin/feature-login
Additional Tips
- Cloning all branches: If you decide you need more than just the one branch, you can clone the entire repository (
git clone <repository-url>
) and then fetch all branches usinggit fetch --all
. - Cloning to a new branch: If you want to clone a branch and then start a new branch from that point, first clone the branch as described above, then create a new branch with
git checkout -b <new-branch-name>
.
For further reading on cloning git repositories see the official Git documentation.