Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

bash

shell

I am creating a deploy script for a zend application. The scrip is almost done only I want to verify that a tag exists within the repo to force tags on the team. Currently I have the following code:

# First update the repo to make sure all the tags are in cd /git/repo/path git pull  # Check if the tag exists in the rev-list.  # If it exists output should be zero,  # else an error will be shown which will go to the else statement. if [ -z "'cd /git/repo/path && git rev-list $1..'" ]; then          echo "gogo"  else      echo "No or no correct GIT tag found"         exit  fi 

Looking forward to your feedback!

Update

When I execute the following in the command line:

cd /git/repo/path && git rev-list v1.4.. 

I get NO output, which is good. Though when I execute:

cd /git/repo/path && git rev-list **BLA**.. 

I get an error, which again is good:

fatal: ambiguous argument 'BLA..': unknown revision or path not in the working tree. Use '--' to separate paths from revisions 

The -z in the statement says, if sting is empty then... In other words, it works fine via command line. Though when I use the same command in a shell script inside a statement it does not seem to work.

[ -z "'cd /git/repo/path && git rev-list $1..'" ] 

This method what inspired by Validate if commit exists

Update 2

I found the problem:

See Using if elif fi in shell scripts >

sh is interpreting the && as a shell operator. Change it to -a, that’s [’s conjunction operator:

[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ] Also, you should always quote the variables, because [ gets confused when you leave off arguments.

in other words, I changed the && to ; and simplified the condition. Now it works beautiful.

if cd /path/to/repo ; git rev-list $1.. >/dev/null  then      echo "gogo"  else     echo "WRONG"     exit fi 
like image 418
Kim Avatar asked Jul 22 '13 14:07

Kim


1 Answers

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.

like image 104
lxg Avatar answered Sep 28 '22 20:09

lxg