Checkout branch on different remote

40.1k views Asked by At

I have a repo that has another remote upstream besides origin. I can do git checkout origin/master, but when I run git checkout upstream/master, I get:

error: pathspec 'upstream/master' did not match any file(s) known to git.

This does not work either:

$ git fetch upstream
From https://github.com/getsentry/sentry
 * branch            HEAD       -> FETCH_HEAD
$ git co -b asdf --track upstream/master
fatal: Cannot update paths and switch to branch 'asdf' at the same time.
Did you intend to checkout 'upstream/master' which can not be resolved as commit?

How to check out branches on upstream remote as I do on origin remote? My git version is 2.1.2.

4

There are 4 answers

5
Anshul Goyal On BEST ANSWER

Just fetch the refs from the remote (this will fetch all branch, commit, refs etc for the upstream repo)

git fetch upstream

After this, checkout the needed branch (this creates a local copy of the branch)

git checkout -b <branchname> --track upstream/<branchname>

Now if you want to pull the changes in this branch in future, all you need to do is

git pull upstream <branchname>

As mentioned here, try doing an explicit fetch on the branch name:

git fetch upstream master:branch_name
4
nneonneo On

If you just added the remote, you'll need to fetch it so that Git knows which branches are available:

git fetch upstream master

After this you can do

git checkout upstream/master

without any issues.

5
Vasanthakumar Jagannathan On

Please follow the below steps,

Step 01: add new remote using below add command

git remote add testRemote https://repourl.git

Step 02: set the url as remote

git remote set-url testRemote https://repourl.git

Step 03: to pull the branches from new repo

git pull

Step 04: switch to new branch

git checkout branchFromNewremote

Then you can create new branch from the current branch

0
charlie80 On

In more concise way (I'm using git 2.28), you can say

git fetch upstream

and then

git checkout -b <branch_name> --guess

where the --guess flag checks if a branch corresponding to <branch_name> exists on any of the remotes and tracks the corresponding remote (docs here).