Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if tag exists in if/else

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

like image 588
DenCowboy Avatar asked Sep 22 '17 13:09

DenCowboy


People also ask

Does git tag exist?

Creating a tag A common pattern is to use version numbers like git tag v1. 4 . Git supports two different types of tags, annotated and lightweight tags. The previous example created a lightweight tag.

How do I checkout a tag?

In order to checkout a Git tag, use the “git checkout” command and specify the tagname as well as the branch to be checked out. Note that you will have to make sure that you have the latest tag list from your remote repository.

How do you list a tag?

In order to list Git tags, you have to use the “git tag” command with no arguments. You can also execute “git tag” with the “-n” option in order to have an extensive description of your tag list. Optionally, you can choose to specify a tag pattern with the “-l” option followed by the tag pattern.

How do I remove a local tag?

To delete a local git tag simply run the "git tag" command with the -d option and tag name. To know the tag name you can run the "git tag" command with the -l option to list all tags, identify the tag you want to delete.


2 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
like image 193
Eric Renouf Avatar answered Oct 16 '22 18:10

Eric Renouf


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).

like image 41
Dominik Avatar answered Oct 16 '22 20:10

Dominik