Given a git refname, can I detect whether it’s a hash, tag, or branch?

You can probably use the show-ref command to do (mostly) what you want. Given some string, if it refers to a tag then…

git show-ref --verify refs/tags/$thestring

…will be true. If it’s a branch name, then…

git show-ref --verify refs/heads/$thestring

…will be true. If the string fails both of those tests, then…

git rev-parse --verify "$thestring^{commit}"

…will tell you if it otherwise refers to a commit (which could be a complete SHA1, a partial SHA1, HEAD, or possibly something else that doesn’t fall into the previous two categories.

Leave a Comment