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

git

Solution

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.

Problem

I'm writing a script that will take in a specification used as the base for creating a branch. Thus, it will have something like this: ``` git checkout -b $newbranch $startingpoint ``` Now, `startingpoint` can be specified either as a branch name, a tag, or a SHA1. Later in the script, I need to do different things based on what `startingpoint` actually is. Is had thought `git rev-parse` would give me this information, but I cannot seem to bend it to my whim. Is there a git way, preferably a porcelain, to get the information I seek? Update I used the `show-ref` information to craft the following shell function: ``` git_ref_type() { [ -n "$1" ] || die "Missing ref name" if git show-ref -q --verify "refs/heads/$1" 2>/dev/null; then echo "branch" elif git show-ref -q --verify "refs/tags/$1" 2>/dev/null; then echo "tag" elif git show-ref -q --verify "refs/remote/$1" 2>/dev/null; then echo "remote" elif git rev-parse --verify "$1^{commit}" >/dev/null 2>&1; then echo "hash" else echo "unknown" fi return 0 } ``` This seems to work well for now, though it's been only very lightly tested.

Original source