首页 > 解决方案 > 在 IF 语句中使用 Bitbucket 的 $BITBUCKET_TAG 变量

问题描述

我整天都在挠头试图弄清楚这一点。有人可以指出我为什么

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

如果我推送到的分支是master.

但是当我试图通过标签来区分它时

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

它被完全忽略,好像if语句中的代码永远不会到达。

我究竟做错了什么?我尝试以多种方式更改语句,尝试使用正则表达式等均无济于事。任何帮助将不胜感激。

这是一个可重现的示例管道代码:

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

标签: continuous-integrationbitbucketcontinuous-deploymentbitbucket-pipelinesbitbucket-cloud

解决方案


问题是您编写"if"语句的方式:

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

这是一个 bash/unixif语句,它将检查一个文本字符串"test-*"作为分支名称,您可能不会使用它。

您应该使用“字符串包含”测试而不是“字符串等于”测试,如下所示:

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

还要注意这里的yml用法'test-*'...

tags:
  'test-*':

... 与 bash/shell 脚本的解释方式不同'test-*'


推荐阅读