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

时间:2021-01-12 23:44:23

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将给出分支名称,但是如果checkout是标记,这不起作用,在这种情况下它只返回'HEAD'。我需要以某种方式获取这些修订的标记名称。

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
  2. 如果当前结帐是分支的HEAD,我想要分支名称
  3. If it is a detached HEAD, I want the tag name (on the assumption there is a tag)
  4. 如果它是一个分离的HEAD,我想要标签名称(假设有一个标签)

1 个解决方案

#1


45  

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的值,如果它没有分离,或者发出标记名称,如果它是完全匹配的话。否则它会显示错误。

#1


45  

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的值,如果它没有分离,或者发出标记名称,如果它是完全匹配的话。否则它会显示错误。