fetch remote branch with the same name

saeedgnu picture saeedgnu · Jun 11, 2011 · Viewed 13.7k times · Source

I want to fetch a branch from a remote, but my branch name does not start with remote name, for example:

git checkout -b BRANCH origin/BRANCH

It work in some cases, but in some cases I get this error:

fatal: git checkout: updating paths is incompatible with switching branches.

while i am sure that the remote has this branch, and this works:

git checkout -b origin/BRANCH

After that, I have to switch to another branch and rename branch origin/BRANCH to BRANCH, and then switch to BRANCH again... I want to know what that error means.

Answer

CB Bailey picture CB Bailey · Jun 11, 2011

This is why you are getting the error message that you are.

git checkout can do one of two things. If you just specify a branch and don't specify any paths then it will switch your current branch to the branch that you specified.

git checkout mybranch   # switch to branch 'my branch'

If you supply some paths, then git will checkout those paths either from the index or, if you specify a branch, from a given branch.

git checkout myfile   # checkout 'myfile' from index

As you can see, there is a potential ambiguity. What should happen if you had a branch called myfile or a file called mybranch?

The way that git resolves this ambiguity is that it tests the parameter to see whether it matches a branch first, and if not it assumes that the parameter refers to a file. If you had a branch and file with the same name you can force git to treat the parameter as a file with this syntax.

git checkout -- myfile  # treat 'myfile' as a file

The -b option, which creates a new branch, is only valid when you are using the branch switching form of checkout and not when you are checking out specified files from the index.

git checkout -b newbranch myfile  # Illegal. I can't use `-b` when
                                  # I'm checking out files.

If you try git checkout -b newbranch origin/BRANCH and you get this error it means that origin/BRANCH didn't match the name of any branch that you have so git assumed that you must be referring to a file.

To show what remote branch references you have you can do git branch -r. If you don't have a reference to a branch that you think should exist you may have to perform a git fetch to retrieve it from the remote.

If you supply -b but no branch name to base the new branch off, git defaults to using HEAD, i.e. the commit that your current checked out branch is on.

git checkout -b origin/BRANCH

This creates a new local branch called origin/BRANCH based on your current commit. This is, at best, likely to cause you some confusion and doesn't sound like it's what you want at all.