Get git current branch/tag name
Solution 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.
Solution 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
Solution 3
This command can print name in this priority: 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. 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.
edA-qa mort-ora-y
I'm an experienced programmer who has worked in numerous domains such graphic rendering, telecommunications, scientific applications, business processes, video games, financial platforms, and development products. For more about programming visit Musing Mortoray, or check out my live stream. If you’d like private mentoring check out my profile at Codementor. I’m the creator of the Leaf programming language.
Updated on June 03, 2022Comments
-
edA-qa mort-ora-y almost 2 years
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:
- 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)
-
thisismydesign over 4 yearsIf a branch points to a tag and you do
git checkout branch
this command will return the tag. I think the correct order isbranch
->tag
as in the answer from @John Szakmeister which works fine in both cases (checking out branches and tags). -
Dewald Swanepoel over 3 yearsI'm trying to work out under what circumstances this would return the tag name. I mean isnt every tag simply a tag on some branch (be it master or any other branch). This git command will always return the branch first, so why would it ever return the tag?
-
user187557 over 3 yearsBranches refer to commits, and tags refer to commits. If a branch and a tag both refer to the currently-checked-out commit, then this will return the branch. If the currently-checked out commit has a tag, but no branch, this will return the tag. If the currently-checked-out commit has no branch or tag, then this will return the commit ID.