Get git current branch/tag name

限于喜欢 提交于 2019-11-30 13:10:27

问题


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.

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. If it is a detached HEAD, I want the tag name (on the assumption there is a tag)

回答1:


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.




回答2:


This command can print name in this priority: tag > branch > commit

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


来源:https://stackoverflow.com/questions/18659425/get-git-current-branch-tag-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!