Recognize that I am not on a git tag with bash

Viewed 285

I would like to have a bash script that will recognize if the caller is not on a git tag (but on an un tagged branch e.g.). I tried the following:

OUTPUT=$(git describe --exact-match --tags $(git log -n1 --pretty='%h')|grep "fatal:")
if [[ $OUTPUT != "0" ]]; then
    echo "no tag present"
fi

but I get no tag present even if there clearly is a tag and the print out of git describe --exact-match --tags $(git log -n1 --pretty='%h') does not contain fatal:. Why does this not work as expected?

2 Answers

If would be easier to rely on the exit status of that command:

if ! git describe --exact-match --tags $(git log -n1 --pretty='%h') 1>/dev/null 2>&1; then
   echo "no tag present"
fi

If there is no tag, the exit status is 128.
If there is, the exist status is 0.

jthill suggests in the comments:

if msg=`git describe --exact-match --tags @ 2>&1`; then 
    echo tagged $msg; 
else 
    echo not tagged; 
fi

Can I recommend git tag --points-at? For example in one of my repositories: commit b0b1c9c is tagged but the HEAD is not:

$ git tag --points-at b0b1c9c
3.8.0
$ git tag --points-at
(empty)

So you can use test

if [ -z "$(git tag --points-at)" ]; then
    echo "no tag present"
fi
Related