Reputation: 1361
You type the command "git checkout foo".
If there is a branch called "foo" yet no file by that name, it switches to the branch -- and if there is a file by that name and no such branch, it updates the file "foo".
But I wonder --- is there a way to enter the command so that Git will unconditionally interpret "foo" as the name of a branch no matter what? This includes (but is not limited to) the specification that if there is no branch called "foo", the operation will fail even if a file by that name exists.
So - is there any way to do this?
Thanks.
Upvotes: 10
Views: 19816
Reputation: 29
Kindly try the below commands, it works for me.
$ git checkout <existing_branch>
$ git checkout -b <new_branch>
$ git checkout branch
Upvotes: -1
Reputation: 34145
Just checked the behaviour of git 2.1.2 and checkout always interprets the name as a branch name. You can force it to be a file instead using ./foo
.
In your case git checkout foo
will always try to switch to branch foo
.
If you want to force the argument to be a branch, so that even if a file is matching it's not updated, you can try to trick git using git checkout -B foo foo
. If foo
exists, git will check it out and update the branch pointer to itself. If it doesn't, the new branch will not be created, because the start point is missing.
Upvotes: 2
Reputation: 11607
Yes, from the reference, there is this usage:
git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>…
In your case, that boils down to:
git checkout foo --
Here, foo
corresponds to <tree-ish>
and --
says that anything after this is referring to file names. So, if you use the above command (with no file names after --
) it will fail if there is no tree-ish (branch) named foo
:
fatal: invalid reference: foo
Upvotes: 15
Reputation: 249113
You can add an explicit check if the branch name exists first:
git show-ref --verify --quiet refs/heads/foo && git checkout foo
That will make sure the branch exists and if it does, check it out. Yes, there is a race condition (the branch could be deleted in between), but hopefully that's not a problem in practice.
Is there a better way to find out if a local git branch exists?
Upvotes: 2