Shell – check if a git tag exists in an if/else statement

Why so complicated? Here’s a dead-simple solution (based on cad106uk’s approach further down the page):

version=1.2.3

if [ $(git tag -l "$version") ]; then
    echo yes
else
    echo no
fi

It is not necessary to compare the output of git tag -l with the version number, because the output will be empty if the version is not found. Therefore it’s sufficient to test if there’s any output at all.

Note: The quotes around $version are important to avoid false positives. Because if $version is empty for some reason, git tag -l would just list all tags, and the condition would always be true.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)