Somebody pushed a branch called test
with git push origin test
to a shared repository. I can see the branch with git branch -r
.
If the branch is on something other than the origin
remote I like to do the following:
$ git fetch
$ git checkout -b second/next upstream/next
This will checkout the next
branch on the upstream
remote in to a local branch called second/next
. Which means if you already have a local branch named next it will not conflict.
$ git branch -a
* second/next
remotes/origin/next
remotes/upstream/next
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.
Use:
git checkout -b <BRANCH-NAME> <REMOTE-NAME>/<BRANCH-NAME>
Other answers do not work with modern Git in my benign case. You might need to pull first if the remote branch is new, but I haven't checked that case.
I use the following command:
git checkout --track origin/other_remote_branch
Sidenote: With modern Git (>= 1.6.6), you are able to use just
git checkout test
(note that it is 'test' not 'origin/test') to perform magical DWIM-mery and create local branch 'test' for you, for which upstream would be remote-tracking branch 'origin/test'.
The * (no branch)
in git branch
output means that you are on unnamed branch, in so called "detached HEAD" state (HEAD points directly to commit, and is not symbolic reference to some local branch). If you made some commits on this unnamed branch, you can always create local branch off current commit:
git checkout -b test HEAD
I found a comment buried below which seems to modernize this answer:
@Dennis:
git checkout <non-branch>
, for examplegit checkout origin/test
results in detached HEAD / unnamed branch, whilegit checkout test
orgit checkout -b test origin/test
results in local branchtest
(with remote-tracking branchorigin/test
as upstream) – Jakub Narębski Jan 9 '14 at 8:17
emphasis on git checkout origin/test
Simply run git checkout
with the name of the remote branch. Git will automatically create a local branch that tracks the remote one:
git fetch
git checkout test
However, if that branch name is found in more than one remote, this won't work as Git doesn't know which to use. In that case you can use either:
git checkout --track origin/test
or
git checkout -b test origin/test
In 2.19, Git learned the checkout.defaultRemote configuration, which specifies a remote to default to when resolving such an ambiguity.