How to check if tag exists in if/else

Viewed 11553

How can I check if a tag exists in my GIT repo. I get as input some tagname and I have to check if it's a valid tag with a if else statement. TAG="tagname"

I tried:

if [ git rev-parse ${TAG} >/dev/null 2>&1 ]; then
  echo "tag exists";
else
  echo "tag does not exist";

But it didn't work

3 Answers

You can use if with a command without test (or it synonym [) and the if command will treat the exit status as the conditional. If it exits with "success" (i.e., 0) then it's true, otherwise it's false:

if git rev-parse "$TAG" >/dev/null 2>&1; then
  echo "tag exists";
else
  echo "tag does not exist"
fi

Easier and cleaner solution

if git show-ref --tags tag1 --quiet; then
  echo "tag exists"
else 
  echo "tag doesn't exist or error in command"
fi

git show-ref exits with exit-code 1 if a tag isn't found (see Git code, didn't find doc for it). There are other if-constructs to check for exit-codes, though (see e.g. this question).

Restrict git rev-parse to only tags

git rev-parse --tags=$TAG only finds tags (the = is necessary), whereas git rev-parse $REF finds all kind of revisions (i.e. also branches and SHAs).

I found only

git rev-parse "refs/tags/$TAG" >/dev/null 2>&1

gives a reliable indication of whether $TAG is an existing tag.

Related