12

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

DenCowboy
  • 13,884
  • 38
  • 114
  • 210
  • Use the exit status returned from the command and so run the command and then use the if statement on $? to find the tag. – Raman Sailopal Sep 22 '17 at 13:35
  • @RamanSailopal is this possible to do in one if statement? (nothing above the if) – DenCowboy Sep 22 '17 at 13:37
  • You are missing a `fi` at the end. (Unrelated: `[[` is to be preferred over `[`.) – Micha Wiedenmann Sep 22 '17 at 13:38
  • @RamanSailopal There is no reason to run the command and use the exit status as you suggested. The `if [[ ....]` is perfectly fine. – Micha Wiedenmann Sep 22 '17 at 13:39
  • It won't work unless the whole git statement is placed in $() Using $? is an alternate way of doing it but if the poster cannot insert anything above the if statement then using $(git rev-parse ${TAG} >/dev/null 2>&1) is the best way to go. – Raman Sailopal Sep 22 '17 at 13:43
  • Does this answer your question? [Shell - check if a git tag exists in an if/else statement](https://stackoverflow.com/questions/17790123/shell-check-if-a-git-tag-exists-in-an-if-else-statement) – Martin Nov 09 '22 at 14:56

3 Answers3

15

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
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
11

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

Dominik
  • 2,283
  • 1
  • 25
  • 37
  • `git rev-parse --tags=$TAG` doesn't work for me on either Windows or Linux, but `git rev-parse $REF` does, however, as you say it also finds branches, not just tags. – CJ Dennis Sep 29 '21 at 10:34
  • @CJDennis Strange. I've tested it on MacOS with `git` from Homebrew (version `2.28.0`) only, though. Perhaps the `--verify` parameter gives some insight? – Dominik Sep 29 '21 at 15:27
0

I found only

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

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

TJahns
  • 197
  • 1
  • 9