195

I've forked from a repo on GitHub. I want to get the code from a branch on another user's fork.

Must I clone this user's whole repo to a separate local repo or can I do something like git checkout link_to_the_other_users_branch?

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
Christian
  • 7,433
  • 4
  • 36
  • 61

2 Answers2

370
$ git remote add theirusername git@github.com:theirusername/reponame.git
$ git fetch theirusername
$ git checkout -b mynamefortheirbranch theirusername/theirbranch

Note that there are multiple "correct" URIs you can use for the remote when you add it in the first step.

  • git@github.com:theirusername/reponame.git is an SSH-based URI
  • https://github.com/theirusername/reponame.git is an HTTPS URI

Which one you prefer to use will depend on your situation. GitHub has a help article explaining the difference and helping you choose: Choosing a URL for your remote repository

amalloy
  • 89,153
  • 8
  • 140
  • 205
  • 1
    What does that last line do? – Andrew Downes Jul 10 '15 at 15:43
  • 3
    The last line checks out a new branch called `mynamefortheirbranch` with its start point set to the head of `theirusername/theirbranch`. – Louis Simoneau Jul 15 '15 at 01:16
  • 4
    I get *Fatal: cannot update paths and switch to branch 'xyz' at the same time. Did you intend to checkout 'xyz/xyz' which can not be resolved as commit?* – The Onin Nov 03 '15 at 18:39
  • 2
    Did not work with me. – Ahmed May 29 '19 at 16:35
  • @amalloy It is creating a branch as expected but not allowing to push the branch in my current fork. Getting this message " To push to the upstream branch on the remote, use git push krupa-fork HEAD:develop To push to the branch of the same name on the remote, use git push krupa-fork HEAD" – javaGroup456 Oct 24 '19 at 08:36
  • after the first command of adding remote- ``$ git fetch theirusername theirbranchname:yourbranchname`` and the branch will be fetched and added to your local forked repo. Then do the push if needed. – Vikrant May 07 '20 at 14:22
45

amalloy's suggestion didn't work for me. This did:

git remote add theirusername https://github.com/theirusername/reponame
git fetch theirusername
git checkout -b mynamefortheirbranch theirusername/theirbranch

Resources:

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79