git clone a specific branch

# Check the branch name before cloning
git ls-remote --heads https://github.com/user/repo.git

# Clone one existing branch
git clone --branch feature/login --single-branch https://github.com/user/repo.git
fatal: Remote branch master not found in upstream origin
fatal: invalid reference: master
fatal: reference is not a tree: origin/master

You only need one branch of a large repository, or you want to clone a non-default branch directly.

Check the remote ref instead of guessing main or master

The default branch is not always named main or master. An invalid reference error means that Git cannot resolve the name you supplied to a branch, tag, or commit in the current repository.

List the remote heads before choosing the branch. This also catches spelling and case differences in names such as feature/Login and feature/login.

# Before cloning
git ls-remote --heads https://github.com/user/repo.git

# After a remote already exists
git remote -v
git fetch origin
git branch --remote

Clone an existing branch and verify the checkout

Pass the exact branch name to --branch. Add --single-branch when the repository does not need other remote branches, such as a focused CI checkout.

git clone --branch feature/login --single-branch https://github.com/user/repo.git
cd repo
git branch --show-current
git log -1 --oneline

Create a local branch from a remote branch

If the repository is already cloned, fetch the remote ref and create a local tracking branch. Do not run git switch master until origin/master appears in the remote branch list.

git fetch origin
git branch --remote

git switch --track -c feature/login origin/feature/login

Fetch more history when the object is missing

A valid branch name can still point to an object that a shallow clone does not have locally. If the failure involves an older commit, fetch more history or convert the clone before retrying.

git rev-parse --is-shallow-repository
git fetch --deepen=100 origin

# If the full history is required
git fetch --unshallow origin

Clone with only the latest commit (shallow + single branch)

Fastest option for CI/CD — downloads only the tip of one branch.

git clone --depth 1 --branch feature/login --single-branch https://github.com/user/repo.git

Switch to a different branch after cloning

Fetch the remote branch first, then create a local branch that tracks it. If the fetch reports that the branch does not exist, verify the exact remote name with git branch --remote.

git fetch origin other-branch
git switch --track -c other-branch origin/other-branch

Clone a specific tag

Checking out a tag leaves the repository in detached HEAD state. Create a branch before committing changes.

git clone --branch v2.1.0 --single-branch https://github.com/user/repo.git
cd repo
git switch -c work-from-v2.1.0