Git change branch when file of same name is present

venky picture venky · Aug 15, 2014 · Viewed 23.3k times · Source

I have in my git repo, a file named xyz. Coincidently, I also have a branch named xyz. Presently I am on master, but I want to checkout to branch xyz. The command to be used is simple

$ git checkout xyz

But this would checkout the file xyz to the present HEAD. How would I change my branch to branch xyz?

Answer

VonC picture VonC · Aug 15, 2014

As illustrated by commit a047faf (git 1.8.4.3+), you can also try:

git checkout xyz --

(Note: the error message will be clearer with Git 2.21, Q1 2019)

That would make clear that the xyz part is a branch or commit, while everything after -- must be a path (here no path is provided). See more here on the double-hyphen convention.

If you try without the '--', that might or might not work, as shown in "Why does git checkout <remote_branchname> not create new tracking branch?":

git checkout name does:

  • if it's local branch or explicit remote branch, switch to it.
  • if it's a tracked path, reset it
  • if it's a remote branch, create a tracking branch and switch to it.

And its behavior isn't always the same. Hence the '--' to provide a clear disambiguation.


Update August 2019, Git 2.23+

git checkout is too confusing and is replaced with:

  • git switch: meaning git switch xyz will work even if you have a file xyz,
  • git restore: meaning git restore xyz will work even if you have a branch xyz.

Plus, as I explain in "Why did my Git repo enter a detached HEAD state?", no more unexpected detached HEAD.