How to checkout a remote branch in git

Why would you want to checkout a remote branch?

While working on a shared repository, colleagues may need access to each other’s repositories.

That can be done in three steps:

  1. fetch all remote branches
  2. Check branches available for checkout
  3. Make a local working copy of the branch
svg viewer

1. Fetching all remote branches

First, fetch all the remote branches from the repository. Assuming that your remote name is origin, you can do it like this:

git remote
# origin
git fetch origin

2. Check branches available for checkout

Then you can check all the branches that are available for checkout, like this:

git branch -a

The output of this command will be all the branches available in the local repository, along with all the branches fetched from the remote. The branches fetched from the remote origin would be preceded by remotes/origin/.


3. Making a local copy of the branch

You cannot make changes in somebody else’s branch. In order to work on someone’s branch, you would have to make a local copy of it, which can then be pushed to the remote host:

git checkout -b <name-your-branch> origin/<name-of-remote-branch>

After this, you can start working on your copy of the fetched remote branch!

Copyright ©2024 Educative, Inc. All rights reserved