Alex Rivera | Logout

How can I check out a remote Git branch?

Asked 2009-11-23T14:23:46.150
8882

How do I check out the remote test branch? I can see it with git branch -r. I tried:

  • git checkout test, which does nothing
  • git checkout origin/test gives * (no branch)
Edit
Report

3 Answers

11967

The answer has been split depending on whether there is one remote repository configured or multiple. The reason for this is that for the single remote case, some of the commands can be simplified as there is less ambiguity.

Updated for Git 2.23: For older versions, see the section at the end.

With One Remote

In both cases, start by fetching from the remote repository to make sure you have all the latest changes downloaded.

$ git fetch

This will fetch all of the remote branches for you. You can see the branches available for checkout with:

$ git branch -v -a

...
remotes/origin/test

The branches that start with remotes/* can be thought of as read only copies of the remote branches. To work on a branch you need to create a local branch from it. This is done with the Git command switch (since Git 2.23) by giving it the name of the remote branch (minus the remote name):

$ git switch test

In this case Git is guessing (can be disabled with --no-guess) that you are trying to checkout and track the remote branch with the same name.

With Multiple Remotes

In the case where multiple remote repositories exist, the remote repository needs to be explicitly named.

As before, start by fetching the latest remote changes:

$ git fetch origin

This will fetch all of the remote branches for you. You can see the branches available for checkout with:

$ git branch -v -a

With the remote branches in hand, you now need to check out the branch you are interested in with -c to create a new local branch:

$ git switch -c test origin/test

For more information about using git switch:

$ man git-switch

Prior to Git 2.23

git switch

answered 2009-11-23T14:26:08.970
129

This will DWIM for a remote not named origin (documentation):

git checkout -t remote_name/remote_branch

To add a new remote, you will need to do the following first:

git remote add remote_name location_of_remote
git fetch remote_name

The first tells Git the remote exists, the second gets the commits.

answered 2012-04-27T22:37:01.830
18

git branch -r says the object name is invalid, because that branch name isn't in Git's local branch list. Update your local branch list from origin with:

git remote update

And then try checking out your remote branch again.

This worked for me.

I believe git fetch pulls in all remote branches, which is not what the original poster wanted.

answered 2013-06-06T12:21:48.030

Your Answer