Search code examples
continuous-integrationbitbucketcontinuous-deploymentbitbucket-pipelinesbitbucket-cloud

Using Bitbucket's $BITBUCKET_TAG variable in an IF statement


I've been scratching my head all day trying to figure this out. Could somebody point me out as to why

- if [ $BITBUCKET_BRANCH == 'master' ]; echo "Do master branch stuff"; fi

works just fine when trying to run some code if the branch I pushed to is master.

But when I'm trying to distiguish it by tags with

- if [ $BITBUCKET_TAG == 'test-*' ]; then echo "Do test tag stuff"; fi

it is completely ignored, as if the code inside the if statement is never reached.

What am I doing wrong? I tried to change the statements in multiple ways, tried using regex, etc. to no avail. Any help would really be appreciated.

Here's a reproducible sample pipeline code:

image: node:12.16.0
options:
  docker: true

definitions:
  steps: 
    - step: &if-test
        name: If test
        script:   

          - if [ $BITBUCKET_BRANCH == 'master' ]; then echo "Do master branch stuff"; fi

          - if [ $BITBUCKET_TAG == 'test-*' ]; then echo "Do test tag stuff"; fi

          - if [ $BITBUCKET_TAG == 'staging-*' ]; then echo "Do staging tag stuff"; fi

pipelines:
  branches:
    master: 
      - step: *if-test

  tags:    

    'test-*': 
      - step: *if-test

    'staging-*': 
      - step: *if-test

Solution

  • The problem is the way you have coded the "if" statement:

    if [ $BITBUCKET_TAG == 'test-*' ];
    

    This is a bash/unix if statement, which will check for a literal string "test-*" as the branch name, which you probably don't use.

    You should use a 'string contains' test instead of a 'string equals' test, like this:

    if [[ $BITBUCKET_TAG == *"test-"* ]];
    

    Also note that the yml usage of 'test-*' here...

    tags:
      'test-*':
    

    ... is different to how a bash/shell script interprets 'test-*'.