获取 git 当前分支/标签名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18659425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get git current branch/tag name
提问by edA-qa mort-ora-y
How can I get the current branch or tag name for my working copy? I have seen references that indicate rev-parse --abbrev-ref HEAD
will give branch name, but this doesn't work if the checkout is of a tag, in which case it just returns 'HEAD'. I need to somehow get the tag name of these revisions.
如何获取工作副本的当前分支或标记名称?我已经看到了表明rev-parse --abbrev-ref HEAD
会给出分支名称的引用,但是如果结帐是标签,则这不起作用,在这种情况下,它只返回“HEAD”。我需要以某种方式获取这些修订的标签名称。
To be clear, I want one of two possible names:
明确地说,我想要两个可能的名字之一:
- If the current checkout is the HEAD of a branch, I want the branch name
- If it is a detached HEAD, I want the tag name (on the assumption there is a tag)
- 如果当前结帐是分支的HEAD,我想要分支名称
- 如果它是一个分离的 HEAD,我想要标签名称(假设有一个标签)
回答by John Szakmeister
I think you want this:
我想你想要这个:
git symbolic-ref -q --short HEAD || git describe --tags --exact-match
That will output the value of HEAD, if it's not detached, or emit the tag name, if it's an exact match. It'll show you an error otherwise.
这将输出 HEAD 的值,如果它没有分离,或者发出标签名称,如果它是完全匹配的。否则它会向您显示错误。
回答by Xiaohui Zhang
This command can print name in this priority: tag
> branch
> commit
此命令可以按此优先级打印名称:tag
> branch
>commit
git describe --tags --exact-match 2> /dev/null \
|| git symbolic-ref -q --short HEAD \
|| git rev-parse --short HEAD