How do I fetch only one branch of a remote Git repository?

I'd like to grab a single branch (not all of them) of a remote repository and create a local tracking branch that can track further updates to that remote branch. The other branches in the remote repository are very big, so I'd like to avoid fetching them. How do I do this?


Solution 1:

git fetch <remote_name> <branch_name>

Worked for me.

Solution 2:

One way is the following:

git fetch <remotename> <remote branch>:refs/remotes/<remotename>/<local branch>

This does not set up tracking though.

For more information, see the documentation of git fetch.

EDIT: As @user1338062 notes below: if you don't already have a local clone of the repository where you want to add the new branch, but you want to create a fresh local repository, then the git clone --branch <branch_name> --single-branch <repo_url> provides a shorter solution.