简体   繁体   English

获取 git 当前分支/标签名称

[英]Get git current branch/tag name

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'.我已经看到引用表明rev-parse --abbrev-ref HEAD将给出分支名称,但是如果结帐是标签,则这不起作用,在这种情况下它只返回“HEAD”。 I need to somehow get the tag name of these revisions.我需要以某种方式获取这些修订的标签名称。

To be clear, I want one of two possible names:明确地说,我想要两个可能的名字之一:

  1. If the current checkout is the HEAD of a branch, I want the branch name如果当前结帐是分支的HEAD,我想要分支名称
  2. If it is a detached HEAD, I want the tag name (on the assumption there is a tag)如果它是一个分离的 HEAD,我想要标签名称(假设有一个标签)

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.这将输出 HEAD 的值,如果它没有分离,或者发出标签名称,如果它是完全匹配的。 It'll show you an error otherwise.否则它会向您显示错误。

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

This command can print name in this priority: branch > tag > commit id这个命令可以在这个优先级中打印名称: branch > tag > commit id

git symbolic-ref --short -q HEAD \
  || git describe --tags --exact-match 2> /dev/null \
  || git rev-parse --short HEAD

Merged @xiaohui-zhang's answer and @thisismydesign's comment.合并@xiaohui-zhang 的回答和@thisismydesign 的评论。 I keep coming back to this question every few months, and this is the answer I end up with, so I thought I'd post it.我每隔几个月就会回到这个问题,这就是我最终得到的答案,所以我想我会发布它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM