Git change branch when file of same name is present
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
: meaninggit switch xyz
will work even if you have a filexyz
,git restore
: meaninggit restore xyz
will work even if you have a branchxyz
.
Plus, as I explain in "Why did my Git repo enter a detached HEAD state?", no more unexpected detached HEAD.
While VonC's solution works, I can never remember the syntax, so I typically use a more low-tech solution:
$ (cd somedir && git checkout my-branch)
Or, if you don't have any subdirectories:
$ (cd .git && git -C .. checkout my-branch)
It's easier to remember and it works ;-)