Here is a brief shell script (tested in Bash, not confirmed if it works on ash, etc.). It will set the git_tag
variable to the name of the currently checked-out tag, or leave it blank if the checkout is not tagged.
git_tag=''
this_commit=`git log --pretty=format:%H%n HEAD^..`
for tag in `git tag -l`; do
tag_commit=`git log --pretty=format:%H%n tags/$tag^..tags/$tag`
if [ "$this_commit" = "$tag_commit" ]; then
# This is a tagged commit, so use the tag.
git_tag="$tag"
fi
done
Comment by Jakub Narębski:
This solution reduces to looping over all tags, and checking if they point to corrent commit, i.e. object pointed by HEAD. Using plumbing commands, i.e. commands meant for scripting, this can be written as:
this_commit=$(git rev-parse --verify HEAD)
git for-each-ref --format="%(*objectname) %(refname:short)" refs/tags/ |
while read tagged_object tagname
do
if test "$this_commit" = "$tagged_object"
then
echo $tagname
fi
done
This would print all tags that point to current commit.