Is there a way to make a "git checkout" and * force * argument that will be interpreted as the branch name?

You enter the command "git checkout foo".

If there is a branch with the name "foo", but there is no file with this name, it switches to the branch - and if there is a file with this name and does not have such a branch, it updates the file "foo".

But I wonder --- is there a way to enter the command so that Git unconditionally interprets "foo" as the branch name no matter what? This includes (but is not limited to) the specification that if there is no branch named "foo", the operation will fail even if a file with the same name exists.

So - is there a way to do this?

Thanks.

+6
source share
3 answers

Yes, from the help, this is using:

git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>… 

In your case, it comes down to:

 git checkout foo -- 

Here foo corresponds to <tree-ish> , but -- says that everything after that refers to the file names. Thus, if you use the above command (without file names after -- ), it will fail if there is no tree (branch) named foo :

 fatal: invalid reference: foo 
+13
source

Just checked the behavior of git 2.1.2, and the check always interprets the name as a branch name. You can make it be a file instead of ./foo .

In your case, git checkout foo will always try to switch to the foo branch.

If you want to force the argument to be a branch, so even if the file matches it, it is not updated, you can try to trick git with git checkout -B foo foo . If foo exists, git will check it and update the branch pointer to itself. If this is not the case, a new branch will not be created because the starting point is missing.

+2
source

You can add an explicit check if the branch name exists first:

 git show-ref --verify --quiet refs/heads/foo && git checkout foo 

This will make sure that the branch exists, and if so, check it. Yes, there is a race condition (a branch can be deleted between them), but I hope this is not a problem in practice.

Is there a better way to find out if a local git branch exists?

+1
source

Source: https://habr.com/ru/post/978006/


All Articles